﻿/**
*@Date 2010-03-22
*@Description 本文件中包括页面端一些常用JS框架、方法的封装
*/
/**
*@description 定义全局
*/
var Chenxin={};


/**
*@description 登录页面URL，全局
*/
Chenxin.loginUrl='/loginex.aspx';
Chenxin.loadImgUrl='';
Chenxin.progressImgUrl='';



/**
*@description 将config配置项的内容，赋值给tag对象
*@tag被覆盖的目标对象
*@config 用于覆盖的目标对象 
*@return 包括两者属性的对象
*/
Chenxin.apply=function(tag,config){
	if(!tag){
		tag={};
	}
	if(tag&&config&& typeof config=='object'){
		for(var c in config){
			if(c=='scope'){
				tag[c]=config[c];			
			}else{			
				if(typeof(config[c])=='object'){
					if($.isArray(config[c])){
						tag[c]=[];
						for(var i=0;i<config[c].length;i++){
							tag[c].push(config[c][i]);
						}
					}else if(config[c]==null){
						tag[c]=null;
					}else{
						tag[c]={};
						Chenxin.apply(tag[c],config[c]);
					}
				}else{
					tag[c]=config[c];			
				}
			}
		}
	}
}

/**
*@description 将config配置项的内容，在tag对象没有该配置项的情况下，赋值给tag对象
*@tag被覆盖的目标对象
*@config 用于覆盖的目标对象 
*@return 包括两者属性的对象
*/
Chenxin.applyIf=function(tag,config){
	if(!tag){
		tag={};
	}
	if(tag&&config&& typeof config=='object'){
		for(var c in config){			
			if(tag[c]==undefined){				
				if(typeof config[c]=='object'){		
					if($.isArray(config[c])){
						tag[c]=[];
						for(var i=0;i<config[c].length;i++){
							tag[c].push(config[c][i]);
						}
					}else if(config[c]==null){
						tag[c]=null;
					}else{			
						tag[c]={};
						Chenxin.apply(tag[c],config[c]);
					}					
				}else{
					tag[c]=config[c];
				}
			}else{
				if(c!='scope'&&typeof config[c]=='object'&&typeof tag[c]=='object'){
					Chenxin.applyIf(tag[c],config[c]);		
				}				
			}
		}
	}
}

/**
*@description 将config配置项的内容，赋值给tag对象
*@tag被覆盖的目标对象
*@config 用于覆盖的目标对象 
*@return 包括两者属性的对象

Chenxin.apply=function(tag,config){
	if(!tag){
		tag={};
	}
	if(config){
		for(var c in config){
			tag[c]=config[c];
		}
	}
}*/

/**
*@description 将config配置项的内容，在tag对象没有该配置项的情况下，赋值给tag对象
*@tag被覆盖的目标对象
*@config 用于覆盖的目标对象 
*@return 包括两者属性的对象

Chenxin.applyIf=function(tag,config){
	if(!tag){
		tag={};
	}
	if(config){
		for(var c in config){
			if(!tag[c]){
				tag[c]=config[c];
			}
		}
	}
}*/

/**
*@description 类的继承方法
*@superclass 父类
*@constructor JSON扩展项内容
*@return 子类
*/
Chenxin.extend=function(superclass, extendConfig){
	var clazz=function(config){
		for(var a in config){
			this[a]=config[a];
		}
		this.initComponent.apply(this,arguments);
	}
	
	//如果无参数,直接返回类.
	if(arguments.length == 0){
		return clazz;
	}
	

	//如果无父类,此时constructor应该为一个纯对象,直接复制属性返回.
	if(!superclass){
		Chenxin.apply(clazz.prototype, extendConfig);
		return clazz;
	}

	var absObj = clazz.prototype;
	var sprPropty = superclass.prototype;

	if(sprPropty){
	  
			//用于访问父类方法
	  clazz.superclass = sprPropty;
	  
	  Chenxin.apply(absObj, sprPropty);//将父类的属性复制给子类
	  //调用属性构造函数创建属性,这个是实现关键.
	  Chenxin.apply(absObj,extendConfig);
	  //$.extend(absObj, extendConfig);//sprPropty.constructor(extendConfig));
	  

	  // 子类实例直接通过obj.superclass访问父类属性,
	  // 如果不想造成过多引用,也可把这句注释掉,因为多数时候是没必要的.
	  absObj.superclass = sprPropty;
	  //
	  //clazz.constructor = constructor;
	}

	return clazz;
}

/**
*未完待续
*/
Chenxin.ns=function (nameSpaceStr){
	/*
	var nameSpaceLevel=nameSpaceStr.split('.');	
	
	if(nameSpaceLevel.length){
		if(!eval(nameSpaceLevel[0])==false){
			eval('var '+nameSpaceLevel[0]+'={};var t='+nameSpaceLevel[0]);
		}else{
			
		}
	}*/
};


/**
*@description 定义表单内容的命名空间
*/
Chenxin.FormCommon={};

/**
*@description 动态加载到本地的数据，存放数据字典等内容
*/
Chenxin.data={};

/**
*@description 动态加载的组织结构
*/
Chenxin.data.struct={
	store:[],//数据仓库，保存数据用
	map:{}//映射，配合store，用fatherid为变量名，保存store的index;例如：xxx:{index:1}，城市及数据为city标记
};
				
/**
*@description 定义默认空函数
*/
Chenxin.emptyFn=undefined;


/**
* @static   包装ajax方法，处理掉了success=-1(sesseion过期) 或者 success=0(操作逻辑错误) 两种情况
*  成功和失败的方法变为  onSuccess 和 onError ， 其他参数相同
*  @example Chenxin.ajax({
				url: 'login.aspx',
				params:param,
				method : 'POST',
				scope:this,
				onSuccess:function(data,msg){
				},
				onError:function(){
				
				}					
			}); 
*/
Chenxin.ajax=function (option){
	Chenxin.apply(option,{
		success: function(result){
			try{	
				if(typeof(result)=='string'){				
					var s=result;
					var reg=new RegExp("\r\n","g");
					s=s.replace(reg, "");
					reg=new RegExp("\r","g");
					s=s.replace(reg, "\\r");
					reg=new RegExp("\n","g");
					s=s.replace(reg, "\\n");
					eval('result='+s);
				}					
			}catch(e){	
				//alert(option.url);
				alert('数据格式返回错误！');
				if(option.onWrong){
					option.onWrong.call(option.scope,result);					
				}
				return;
			}
			if(result.success==-1){//登录超时	
				alert(result.msg||'登录超时，请重新登录！');
				
				window.location.href=Chenxin.loginUrl;
			}else if(result.success==0){//执行失败
				alert(result.msg);
				if(option.onFail){
					option.onFail.call(option.scope,result.data,result.msg);
				}
			}else if(option.onSuccess){
				option.onSuccess.call(option.scope,result.data,result.msg);
			}
		},
		error: function(){
			if(option.onError){
				alert('服务器无法响应，请稍候再试！');
				option.onError.call(option.scope);
			}
			return false;
		}
	});
	
	option.url+=option.url.indexOf('?')==-1?'?':'&'+'_r='+Math.random()*10000000000;
	Chenxin.applyIf(option,{dataType:'text'});
	$.ajax(option);
}

/**
*@description 对话框
*/
Chenxin.Msg={
	currentDomId:'',
	icon:{
		cycle:'x-msg-icon-cycle',
		progress:'x-msg-icon-progress',
		info:'x-msg-icon-info',
		warring:'x-msg-icon-warring',
		wrong:'x-msg-icon-wrong',
		next:'x-msg-icon-next'
	},
	/**
	*@description 创建对话框
	*@config{
		dom:'hello',
		icon:Chenxin.Msg.icon.cycle,
		title:'请等待',
		content:'加载中……',
		btnConfig:{
			y:true,
			n:false
		}
	} 
	*/
	create:function(config){	
		
		if(!config.id){
			Chenxin.Msg.currentDomId=(Math.random()*100000+'');
			Chenxin.Msg.currentDomId=Chenxin.Msg.currentDomId.substr(0,Chenxin.Msg.currentDomId.indexOf('.'));	
			config.id=Chenxin.Msg.currentDomId;
		}else{
			if($('#chenxin-msg-maskdiv-'+config.id).length){
				// $('#chenxin-msg-maskdiv-'+config.id).show();
				// $('#chenxin-msg-masktable-'+config.id).show();
				$('#chenxin-msg-maskdiv-'+config.id).remove();
				$('#chenxin-msg-masktable-'+config.id).remove();
				//return;
			}
		}
		
		var setting='';
		var _alert='';
		var domId='';
		var isBody=(config.dom==document.body);
		
		if(!isBody){
			var postion=Chenxin.Fn.getDomPosition(config.dom);
			setting+='left:'+postion.x1+'px;';
			setting+='top:'+postion.y1+'px;';
			setting+='width:'+postion.width+'px;';
			setting+='height:'+postion.height+'px;';
			setting+='border-width:0px;';
		}else{			
			setting+='left:0px;';
			setting+='top:0px;';
			setting+='width:100%;';
			setting+='height:100%;';
		}
		if(config.opcity==undefined){
			config.opcity=10;
		}
		
		_alert='<div id="chenxin-msg-maskdiv-'+config.id+'" class="x-mask-div x-mask-opcity-'+config.opcity+'" style="'+setting+'" ></div>';	
		
		if(!isBody){
			_alert+='<table id="chenxin-msg-masktable-'+config.id+'" class="x-msg-table" style="'+setting+'"><tr><td style="text-align:center;">';	
			_alert+='<table class="'+(config.tabCls||'')+'" style="'+config.tabStyle+'">';
		}else{
			_alert+='<table id="chenxin-msg-masktable-'+config.id+'" class="'+(config.tabCls||'')+' x-msg-table" style="'+(config.tabStyle||'')+'left:45%;top:35%;">';
		}
		
		//标题
		if(config.title){
			_alert+='<tr><td style="padding:5px;'+(config.isAlert?'background-image:url(\'/images/icon/msg/titlebg.png\');background-repeat:repeat-x':'')+'"><span class="x-msg-title">'+config.title+'</span>'+(config.isAlert?'<em>X</em>':'')+'</td></tr>';
		}
		//内容
		config.content=config.content||'';
		_alert+='<tr><td class="x-msg-content '+config.icon+'">'+config.content+'</td></tr>';
		
		//按钮
		if(config.btnConfig){
			_alert+='<tr><td style="text-align:right; padding-right:10px;"></td></tr>';
		}
		_alert+='</table>';
		
		
		$(document.body).append(_alert);
		if(!isBody){
			_alert+='</td></tr></table>';			
		}
		
		
		$('#chenxin-msg-masktable-'+config.id+' em').live('click',function(){
			Chenxin.Msg.hide(config.id);
			if(config.afterClose){
				config.afterClose();
			}
		});
	},
	destory:function(domId){
		if(!domId){
			domId=Chenxin.Msg.currentDomId;
		}		
		$('#chenxin-msg-maskdiv-'+domId).remove();
		$('#chenxin-msg-masktable-'+domId).remove();
	},
	hide:function(domId){
		if(!domId){
			domId=Chenxin.Msg.currentDomId;
		}
		$('#chenxin-msg-maskdiv-'+domId).hide();
		$('#chenxin-msg-masktable-'+domId).hide();
	}
};

/**
*@description 提示对话框
*/
Chenxin.Msg.alert={
	id:'alert',
	show:function(content,title,icon,closeHander){
		Chenxin.Msg.create({
			id:Chenxin.Msg.alert.id,
			dom:document.body,
			opcity:10,
			isAlert:true,
			tabStyle:'border:solid 1px #ccc;',
			icon:icon||Chenxin.Msg.icon.info,
			title:title||'提示',
			content:content||'有一个错误',
			afterClose:closeHander
		});		
	},
	hide:function(){
		Chenxin.Msg.hide(Chenxin.Msg.alert.id);		
	}
};


/**
*@description 加载中对话框
*/
Chenxin.Msg.Rendering={
	id:'rendering',
	show:function(content){
		Chenxin.Msg.create({
			id:Chenxin.Msg.Rendering.id,
			dom:document.body,
			opcity:0,
			icon:Chenxin.Msg.icon.cycle,
			content:'渲染中，请稍候...'
		});
	},
	hide:function(){
		Chenxin.Msg.hide(Chenxin.Msg.Rendering.id);
	}
};

/**
*@description 加载中对话框
*/
Chenxin.Msg.Loading={
	id:'loading',
	show:function(content){
		Chenxin.Msg.create({
			id:Chenxin.Msg.Loading.id,
			dom:document.body,
			opcity:0,
			icon:Chenxin.Msg.icon.cycle,
			content:'Loading...'
		});
	},
	hide:function(){
		Chenxin.Msg.hide(Chenxin.Msg.Loading.id);
	}
};

/**
*@description 保存中对话框
*/
Chenxin.Msg.Saving={
	id:'saving',
	show:function(){
		Chenxin.Msg.create({
			id:Chenxin.Msg.Saving.id,
			dom:document.body,
			opcity:10,
			icon:Chenxin.Msg.icon.progress,
			title:'Saving...'
		});
	},
	hide:function(){
		Chenxin.Msg.hide(Chenxin.Msg.Saving.id);
	}	
};

/**
*@description 等待对话框
*/
Chenxin.Msg.Waiting={
	id:'waiting',
	show:function(){
		Chenxin.Msg.create({
			id:Chenxin.Msg.Waiting.id,
			dom:document.body,
			opcity:10,
			icon:Chenxin.Msg.icon.progress,
			title:'Waiting...'
		});
	},
	hide:function(){
		Chenxin.Msg.hide(Chenxin.Msg.Waiting.id);
	}	
};

/**
*@description 定义Function功能函数命名空间
*/
Chenxin.Fn={};

/**
*@description 比较日期，如果其中一个参数为空，则返回true，否则，如果date1大于date2返回true
*@date1 第一个日期，格式：2010-1-3
*@date2 第二个日期，格式：2010-1-3
*/
Chenxin.Fn.compareDate=function(date1,date2){
	if(!date1||!date2){
		return true;
	}
	var d1=date1.split('-');
	var d2=date2.split('-');
	
	var a=new Date(d1[0],parseInt(d1[1])-1,d1[2]);
	var b=new Date(d2[0],parseInt(d2[1])-1,d2[2]);
	
	return a>b;
}

/**
*@description 扩展Object的equals方法，比较两个对象的字符串是否相等
*/
Chenxin.Fn.equals=function(obj1,obj2){
	if(obj1==obj2){
		return true;
	}
	return obj1.toString()==obj2.toString();
};

/**
*@description 格式化字符串方法
*@example Chenxin.Fn.stringFormat('hello,{0}{1}','world','1');方法将返回hello,world!;
*/
Chenxin.Fn.stringFormat=function(){
	if(!arguments.length){
		return '';
	}
	var s=arguments[0];
	
	for(var i=0;i<arguments.length-1;i++){
		s=s.replace('{'+i+'}',arguments[i+1]);
	}
	return s;
}

/**
*@description 获取指定ID容器内的表单项JSON
*@formDomId 指定容器的ID
*@comboList DIV下拉框数组
*@emptyInJson 值为空时是否也转换为Json
*@regurn JSON对象 
*/
Chenxin.Fn.getFormJson=function(formDomId,comboList,emptyInJson){
	var json={};
	var filter='';
	if(formDomId){
		filter='#'+formDomId+' ';
	}
	
	//搜索password
	$(filter+':password').each(function(){
		if(this.name){
			json[this.name]=this.value;			
		}
	});
	
	//搜索text控件
	$(filter+':text').each(function(){
		if(this.name){
			if(this.defVal!=this.value){
				json[this.name]=this.value;
			}else{
				json[this.name]='';
			}
		}			
	});
	
	//搜索选中的Checkbox项
	$(filter+':checkbox:checked').each(function(){			
		/**
		*判断此名称的表单项目是否已经存在，
		*存在则追加选中值，否则声明新的属性，并设置值
		*/
		if(this.name){
			if(json[this.name]){
				json[this.name]+=','+this.value;
			}else{
				json[this.name]=this.value;
			}
		}			
	});
	//搜索选中的radio选中值
	$(filter+':radio:checked').each(function(){
		json[this.name]=this.value;
		
	});
	
	//搜索隐藏项的值
	//$(filter+':hidden').each(function(){
	$(filter+'input[type="hidden"]').each(function(){
		if(this.name&&this.value){
			json[this.name]=this.value;
		}			
	});
	
	//搜索textarea项
	$(filter+'textarea').each(function(){
		if(this.name){
			json[this.name]=this.value;
		}			
	});
	
	//搜索selected选中项
	$(filter+'select option:selected').each(function(){
		if(this.parentNode.name){				
			if(json[this.parentNode.name]){
				json[this.parentNode.name]+=','+this.value;
			}else{
				json[this.parentNode.name]=this.value;
			}
		}
	});
	
	if(comboList){	
		//搜索DIV下拉框
		for(var i=0;i<comboList.length;i++){
			var tempItem=comboList[i];
			if(tempItem.getValue()!=tempItem.defVal){
				if(tempItem.inModelType=='val'){					
					if(tempItem.comboType=='wincombo'){
						for(var v in tempItem.inModelName){
							json[v]=tempItem.getValue(v);
						}
					}else{						
						json[tempItem.name]=tempItem.getValue();
					}
					
				}else if(tempItem.inModelType=='txt'){				
					if(tempItem.comboType=='wincombo'){
						for(var v in tempItem.inModelName){
							json[v]=tempItem.getText(v);
						}
					}else{						
						json[tempItem.name]=tempItem.getText();	
					}		
				}else if(tempItem.inModelType=='all'){								
					if(tempItem.comboType=='wincombo'){
						for(var v in tempItem.inModelName){
							json[v]=tempItem.getValue(v);
							json[v]=tempItem.getText(v);
						}
					}else{						
						json[tempItem.name]=tempItem.getValue();
						json[tempItem.txtModelName]=tempItem.getText();
					}		
				
				}
			}
		}
	}
	
	//此参数不传或为false是，删除值为空的字段
	if(!emptyInJson){
		for(var temp in json){
			if((json[temp]+'')==''){
				delete json[temp];
			}
		}
	}
	
	return json;
}

/**
*@description 获取指定ID容器内的表单项JSON
*@formDomId 指定容器的ID
*@comboList DIV下拉框数组
*@model 需要添加到容器表单项的Json对象
*@notAutoInit 如果Model中没有值，是否初始化,设置为true时，系统将不设置初始化值
*@regurn null 
*/
Chenxin.Fn.setFormValue=function(formDomId,comboList,model,notAutoInit){
	var filter='';
	if(formDomId){
		filter='#'+formDomId+' ';
	}
	model=model||{};
	//设置password
	$(filter+':password').each(function(){
		if(this.name){
			if(model&&model[this.name]!=undefined){			
				this.value=model[this.name];
			}else{
				if(!notAutoInit){
					this.value="";				
				}
			}		
		}
	});
	
	//设置text控件
	$(filter+':text').each(function(){
		if(this.name){
			if(model&&model[this.name]!=undefined){			
				this.value=model[this.name];
			}else{
				if(!notAutoInit){
					this.value="";				
				}
			}
		}			
	});
	
	//设置选中的Checkbox项
	$(filter+':checkbox').each(function(){			
		/**
		*判断此名称的表单项目是否已经存在，
		*存在则追加选中值，否则声明新的属性，并设置值
		*/
		if(model[this.name]!=undefined){
			if(model){
				var value=model[this.name]+','
				if(value.indexOf(this.value)!=-1){
					this.checked=true;
				}else{
					this.checked=false;
				}
			}else{
				this.checked=false;
			}
		}else{
			if(!notAutoInit){
				this.checked=false;				
			}	
		}	
	});		
	
	//设置选中的Select项
	$(filter+'select').each(function(){			
		/**
		*判断此名称的表单项目是否已经存在，
		*存在则追加选中值，否则声明新的属性，并设置值
		*/
		if(model[this.name]!=undefined){
			for(var i=0;i<this.options.length;i++){
					
				if(model){
					if(this.options[i].value.indexOf(model[this.name]+',')!=-1){
						this.options[i].selected=true;
					}else{
						this.options[i].selected=false;					
					}
				}else{
					this.options[i].selected=false;						
				}
			}
		}else{
			if(this.options.length&&!notAutoInit){
				this.options[0].selected=true;
			}
		}	
	});
	
	//设置选中的radio选中值
	var radioName='';
	$(filter+':radio').each(function(i){
		if(model&&model[this.name]!=undefined){
			if(this.value==(model[this.name]+'')){
				this.checked=true;
			}else{
				this.checked=false;
			}
		}else{
			if(this.name!=radioName){
				this.checked=true;
				radioName=this.name;
			}else{
				this.checked=false;
			}			
		}
	});
	
	//设置隐藏项的值
	//$(filter+':hidden').each(function(){
	$(filter+'input[type="hidden"]').each(function(){
		if(model&&model[this.name]!=undefined){			
			this.value=model[this.name];
		}else{
			if(!notAutoInit){
				this.value="";				
			}
		}
	});
	
	//设置textarea项
	$(filter+'textarea').each(function(){
		if(model&&model[this.name]!=undefined){			
			this.value=model[this.name];
		}else{
			if(!notAutoInit){
				this.value="";				
			}
		}		
	});
	
	if(comboList){	
		//设置DIV下拉框
		for(var i=0;i<comboList.length;i++){
			var tempItem=comboList[i];
			if(tempItem.comboType=='selectcombo'){//普通Combo
				if(model&&model[tempItem.name]!=undefined){
					if(tempItem.inModelType=='txt'){	
						tempItem.setValeByText(model[tempItem.name]);
					}else{			
						tempItem.setValue(model[tempItem.name]);
					}
				}else{
					if(!notAutoInit){
						tempItem.setValue(tempItem.defVal);					
					}
				}		
			}else if(tempItem.comboType=='treecombo'){//树Combo
			
				if(model&&model[tempItem.name]!=undefined){
					if(tempItem.inModelType=='txt'){	
						tempItem.setValeByText(model[tempItem.name]);
						delete tempItem.qcNode//删除快捷选中点
					}else{	
						tempItem.setValue(model[tempItem.name],model[tempItem.txtModelName]);//同时传入val,txt，不需要Ajax再次加载
						delete tempItem.qcNode//删除快捷选中点
					}
				}else{
					if(!notAutoInit){
						tempItem.setDefValue();
						//tempItem.setValue(tempItem.defVal);					
					}
				}
			}
		}
	}
}

/**
*@description 处理元素的Disable操作
*@obj 元素
*@status 状态，true/false
*/
Chenxin.Fn.handlerDisabled=function(obj,status){
	if(status){
		$(obj).attr('disabled','disabled');
	}else{
		$(obj).removeAttr('disabled');
	}
	obj.disabled=status;
}

/**
*@description 设置表单项的可用性
*@formDomId 指定容器的ID
*@comboList DIV下拉框数组 暂不支持
*@status 状态，true or false
*@regurn null 
*/
Chenxin.Fn.setFormDisableStatus=function(formDomId,comboList,status){
	var filter='';
	if(formDomId){
		filter='#'+formDomId+' ';
	}
	
	//设置password
	$(filter+':password').each(function(){
		Chenxin.Fn.handlerDisabled(this,status);
		//this.disabled=status;
	});
	
	//设置text控件
	$(filter+':text').each(function(){
		Chenxin.Fn.handlerDisabled(this,status);
		//this.disabled=status;
	});
	
	//设置选中的Checkbox项
	$(filter+':checkbox').each(function(){
		Chenxin.Fn.handlerDisabled(this,status);
		//this.disabled=status;
	});		
	
	//设置选中的Select项
	$(filter+'select').each(function(){
		Chenxin.Fn.handlerDisabled(this,status);
		//this.disabled=status;
	});
	
	//设置选中的radio选中值
	$(filter+':radio').each(function(i){
		Chenxin.Fn.handlerDisabled(this,status);
		//this.disabled=status;
	});
	
	
	//设置textarea项
	$(filter+'textarea').each(function(){
		Chenxin.Fn.handlerDisabled(this,status);
		//this.disabled=status;
	});
	
	//设置DIV下拉框
	for(var i=0;i<comboList.length;i++){
		var tempItem=comboList[i];
		tempItem.disable=true;
		if(status){
			tempItem.setDisable();
		}else{
			tempItem.setEnable();
		}
	}
};

/**
*@description 设置表单项可用
*@formDomId 指定容器的ID
*@comboList DIV下拉框数组 暂不支持
*@status 状态，true or false
*@regurn null 
*/
Chenxin.Fn.setFormEnable=function(formDomId,comboList){
	Chenxin.Fn.setFormDisableStatus(formDomId,comboList,false);
};

/**
*@description 设置表单项不可用
*@formDomId 指定容器的ID
*@comboList DIV下拉框数组 暂不支持
*@regurn null 
*/
Chenxin.Fn.setFormDisable=function(formDomId,comboList){
	Chenxin.Fn.setFormDisableStatus(formDomId,comboList,true);
};

/**
*@description 创建JQModel窗体
*
*/
Chenxin.Fn.createJQWin=function(innerHtml,id,className,jqmWidth){
	innerHtml=innerHtml||'';
	id=id||'jqmWindow';
	className=className||'';
	jqmWidth=jqmWidth||'600';
	
	return '<div class="jqmWindow '+className+'" id="'+id+'" style="display:none;width:' + jqmWidth + 'px;">'+innerHtml+'</div>'
}

/**
*@description 创建JQModel窗体标题
*
*/
Chenxin.Fn.createJQTitle=function(title){
	return '<div class="jqmTitle jqDrag"><span class="title">'+title+'</span><span class="jqmClose"></span></div>'
}

/**
*@description 通用获取Model方法
*@modelId ID
*@url 交互地址
*@callBack 执行成功回调方法
*@scope 回调方法传递的作用域
*@op op,默认为getmodel
*/
Chenxin.Fn.getModel=function(modelId,url,callBack,scope,op,param){
	var _data={op:op||'getmodel',modelid:modelId};
	if(param){
		Chenxin.apply(_data,param);
	}
	Chenxin.ajax({
		type: "get",
		dataType: "json",
		url: url,
		data: _data,
		onSuccess: function(data) {
			callBack.call(scope,data.model||data);
		},
		onFail:function(data){
			Chenxin.Msg.Waiting.hide();	

				
			if(scope){
				if(scope.hide){
					scope.hide();
				}
			}			
		},
		onError:function(){
			Chenxin.Msg.Waiting.hide();
			
				
			if(scope){
				if(scope.hide){
					scope.hide();
				}
			}
		}	
	});
}

/**
*@description 导出table为excel,
*@data 要导出的tableHTML内容
*@filename 默认的文件保存名称
*/
Chenxin.Fn.exportToExcel=function(data, filename) {
    if(data){
		filename=filename||'导出数据';
		var objBody = document.getElementsByTagName("body").item(0);
		var objExpTemp = document.getElementById('objExpTemp');

		if (!objExpTemp) {
			objExpTemp = document.createElement("iframe");
			objExpTemp.setAttribute('id', 'objExpTemp');
			objExpTemp.style.display = 'none';
			objExpTemp.src = 'about:blank';
			objBody.appendChild(objExpTemp);
		}

		var myForm = objExpTemp.contentWindow.document.forms['myForm'];
		if (!myForm) {
			objExpTemp.contentWindow.document.write('<div style="display:none"><form name="myForm"><input id="expContent" name="content" type="text" /><input id="expFileName" name="fileName" type="text" /></form></div>');
		}
		var myForm = objExpTemp.contentWindow.document.forms['myForm'];
		var txtData = objExpTemp.contentWindow.document.getElementById('expContent');
		txtData.value = data;
		var txtFileName = objExpTemp.contentWindow.document.getElementById('expFileName');
		txtFileName.value = filename;
		
		myForm.action = '/ExcelTransfer.aspx';
		myForm.method = 'POST';
		myForm.submit();
	}else{
		alert('导出失败，不能导出空数据！');
	}
}

Chenxin.Fn.exportToExcelByServer=function(url, data, filename) {
	filename=filename||'导出数据';
	var objBody = document.getElementsByTagName("body").item(0);
	var objExpTemp = document.getElementById('objExpTemp_all');

	if (!objExpTemp) {
		objExpTemp = document.createElement("iframe");
		objExpTemp.setAttribute('id', 'objExpTemp_all');
		objExpTemp.style.display = 'none';
		objExpTemp.src = 'about:blank';
		objBody.appendChild(objExpTemp);
	}

	var myForm = objExpTemp.contentWindow.document.forms['myForm_all'];
	if (!myForm) {
		objExpTemp.contentWindow.document.write('<div style="display:none"><form name="myForm_all"><input id="expContent" name="content" type="text" /><input id="expFileName" name="fileName" type="text" /></form></div>');
	}
	
	var myForm = objExpTemp.contentWindow.document.forms['myForm_all'];
	
	myForm.action = url+'?'+$.param(data);;
	myForm.method = 'POST';
	myForm.submit();
}

/**
*@description权限检查
*@url 后台交互地址
*@code 后台传递参数code
*@callBack 执行成功的回调函数
*@scope 回调函数作用域
*/
Chenxin.Fn.checkPermit=function(url,code,callBack,scope,data){	
	var _data={op:'checkpermit',code:code};
	if(data){
		Chenxin.apply(_data,data);
	}
	Chenxin.ajax({
		type: "post",
		dataType: "json",
		url: url,
		async:false,
		data: _data,
		onSuccess: function(data,msg) {
			callBack.call(scope,data,msg);
		},
		onFail:function(data,msg){
			callBack.call(scope,data,msg);
		}
	});
},

/**
*@description 获取URL的参数
*@key 要获取的参数名
*/
Chenxin.Fn.getQueryString = function(key) {
	var str = decodeURI(window.location.search);
    var reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)", "i");
    var r = str.substr(1).match(reg);
    if (r != null) {
        return unescape(r[2]);
    } else {
        return null;
    }
};

/**
*@description 根据[{txt:'a',val:'1'}]数组生成CheckBox组
*@items [{txt:'a',val:'1'}]数组
*@name CheckBox控件的name属性
*@width 包裹CheckBox空间的DIV的宽度
*@renderTo 控件组渲染的容器ID，如果没有，函数返回生成的控件组字符串
*/
Chenxin.Fn.createCheckBoxGroup=function(items,name,width,renderTo){
	name=name||'checkboxgroup1';
	width=width||130;
	var html='';
	for(var i=0;i<items.length;i++){
		var t=Math.random()*100000+'';
		var id='cx_'+t.split('.')[0]+'_'+t.split('.')[1];
		html+='<div style="float:left;"><input type="checkbox" name="'+name+'" value="'+items[i].val+'" id="'+id+'"/><label for="'+id+'">'+items[i].txt+'</label></div>';
	}
	if(renderTo){
		$('#'+renderTo).html(html);
		return;
	}
	return html;
}

/**
*@description 删除JSON的所有属性
*/
Chenxin.Fn.initObject=function(obj){
	for(var c in obj){
		delete c;
	}
}

/**
*@description 获得元素位置,大小尺寸信息
*/
Chenxin.Fn.getDomPosition=function(oElement){
	if(typeof(oElement)=='string'){
		oElement=document.getElementById(oElement);
	}
	var p={
		width:oElement.offsetWidth,
		height:oElement.offsetHeight		
	};
	
	if(typeof( oElement.offsetParent ) != 'undefined'){
		for( var posX = 0, posY = 0; oElement; oElement = oElement.offsetParent ){
			posX += oElement.offsetLeft;
			posY += oElement.offsetTop;      
		}		
		p.x1=posX;
		p.y1=posY;
	} else{
		p.x1=oElement.x;
		p.y1=oElement.y;
	}
	p.x2=p.x1+p.width;
	p.y2=p.y2+p.height;
	return p;
}

/**
 * 全角字符转为半角字符
 * @param {String} str 包含全角字符的字符串
 * @return 格式化为半角的字符串
 */
Chenxin.Fn.fullToHalfChar = function(str) {
	if(!str){
		return '';
	}
	if(!str.length){
		return '';
	}

    var myArray = [];
    for (var i = 0; i < str.length; i++) {
        if (str.charCodeAt != null && String.fromCharCode != null) {
            var charCode = str.charCodeAt(i);
            if (charCode > 0xfee0) {
                myArray[i] = String.fromCharCode(charCode - 0xfee0);
            }
            else
                myArray[i] = String.fromCharCode(charCode);
        }
    }
    return myArray.join('');  
}

/**
*@description 绑定数据，绑定到SPAN、DIV等，{a:'1'}绑定到ID为a的容器上
*@model 需要绑定的数据
*@pix 容器ID前缀，同一个页面中，需要多出绑定相同数据的时候，加以区分
*/
Chenxin.Fn.BindData=function(model,pix){
	pix=pix||'';
	for(var m in model){
		$('#'+pix+m).html(model[m]);
	}
}

/**
*@description 注册日期选择器
*/
Chenxin.Fn.RegistDatePicker=function(){
	$('.x-input-date').focus(function() {
		$(this).attr('readonly','readonly');
		WdatePicker({ oncleared: function() { $(this).blur(); }, onpicked: function() { $(this).blur(); } });
	});
};



/**
*@description 定义UI界面命名空间
*/
Chenxin.UI={};


Chenxin.UI.Win=Chenxin.extend(null,{
	autoInit:true,
	id:'',
	renderTo:'',
	hasCloser:true,
	hasFoot:true,
	bodyCls:'x-win-body',
	winCls:'x-win',
	footCls:'x-win-foot',
	titleCls:'x-win-title',
	mainCls:'x-win-main',
	btnCls:'x-button',
	title:'窗体',
	height:0,
	width:600,
	content:'',
	autoScroll:true,
	afterClose:Chenxin.emptyFn,
	afterHide:Chenxin.emptyFn,
	createBtn:Chenxin.emptyFn,
	createBodyDom:function(){
		var _t=$(document.createElement('div'));
		_t.addClass(this.bodyCls||'');
		if(this.height){
			_t.height(this.height);
			if(this.autoScroll){			
				_t.css('overflow','auto');
			}else{				
				_t.css('overflow','hidden');
			}
		}
		return _t;
	},
	createEl:function(){	
		var _t=$(document.createElement('div'));
		_t.addClass(this.winCls||'');
		_t.attr('id',this.id);
		_t.css('display','none');
		_t.width(this.width||600);
		return _t;
	},
	createFootDom:function(){
		var _t=$(document.createElement('div'));
		_t.addClass(this.footCls||'');
		return _t;
	},
	createTitleDom:function(){
		var _t=$(document.createElement('div'));
		_t.addClass('jqDrag');
		_t.addClass(this.titleCls||'');
		
		_t.append('<span class="x-win-title-l"></span><em>'+this.title+'</em><span class="x-win-title-r"></span>');
		
		if(this.hasCloser){
			var _close=document.createElement('a');
			_close.className='x-win-close';
			_close.title='关闭';
			var _this=this;
			$(_close).bind('click',function(){
				_this.close.call(_this);
			});
			_t.append(_close);
			//_t.append('<a class="x-win-close"></a>');
		}
		
		return _t;
	},
	getTitle:function(){
		return this.titleDom.find('em').html();
	},
	setTitle:function(title){
		this.title=title;
		this.titleDom.find('em').html(this.title);
	},
	setWidth:function(width){
		if(!this.width){
			return;
		}
		this.width=width;
		this.el.width(width);
	},
	init:function(){
		if(!this.el){
			this.el=this.createEl();
			
			this.titleDom=this.createTitleDom();		
			this.el.append(this.titleDom);
			
			var _m=$(document.createElement('div'));
			_m.addClass(this.mainCls||'');
			
			this.el.append(_m);
			this.bodyDom=this.createBodyDom();
			_m.append(this.bodyDom);
			if(this.hasFoot){
				this.footDom=this.createFootDom();
				this.initButton(this.footDom);
				_m.append(this.footDom);
			}
			this.bodyDom.append(this.content);
			this.render();		
		}
	},
	initButton:function(renderDom){		
		if(this.createBtn&&renderDom){
			var _b=this.createBtn.call(this);
			for(var i=_b.length-1;i>-1;i--){
				var _a=$(document.createElement('a'));
				//_a.attr('href','#');
				_a.addClass('fr');
				_a.addClass(this.btnCls||'');
				_a.append('<span title="'+_b[i].text+'">'+_b[i].text+'</span>');
				
				if(_b[i].icon){
					_a.find('span').addClss(_b[i].icon);
				}
				var sc=_b[i].scope||this;
				if(_b[i].handler){
					var f=_b[i].handler;
					_a.bind('click',{fn:_b[i].handler,scope:sc},function(e){
						e.data.fn.call(e.data.scope);
					});
				}
				
				renderDom.append(_a);
			}
		}
	},
	render:function(){		
		if(!this.renderTo){
			$(document.body).append(this.el);		
		}else{
			$('#'+this.render).append(this.el);				
		}
		this.el.jqm({ trigger: false}).jqDrag('.jqDrag');
	},
	show:function(){
		this.init();
		this.el.jqmShow();
	},
	close:function(){
		this.el.jqmHide();
		if(this.afterClose){
			this.afterClose.call(this);
		}
	},
	hide:function(){
		this.el.jqmHide();
		if(this.afterHide){
			this.afterHide.call(this);
		}
	},
	resetContent:function(content){
		content=content||this.content;
		this.content=content;
		this.bodyDom.empty();
		this.bodyDom.append(content);
	},
	initComponent:function(){
		if(!this.id){
			throw new Error('id is need!');
		}
		if(this.autoInit){
			this.init();	
		}
	}
});


/**
*@description 下拉框基类
*@extend Selector
*/
Chenxin.UI.Combo = Chenxin.extend(Selector, {
    actionUrl: '',
    addPleaseSelected: true,
    showMode: 'single',
    defVal: '请选择',
    defTxt: '请选择',
    txtModelName: '', //在inModel的时候，inModelType为all时,保存显示值的属性名
    autoLoad: false,
    required: false, //是否必选
    param: {},
    paramType: 'text',
    items: [],
    /**
    *val时，用name属性保存值;
    *txt时，用name属性保存显示值;
    *all时，用name属性保存值，txtModelName属性保存显示值
    */
    inModelType: 'val',
    /**
    *兼容以前的AJAX方法调用，若为new，则调用Chenxin.ajax({});
    *返回数据格式为{success:'',msg:'',data:''}
    */
    typeModel: 'old',//此属性已废弃
    tbxWidth: 90,
	hasPage:false,			//是否有分页
	hasSearch:false,		//是否有查询
	pageSize:20,			//每页显示记录数
	currentPageIndex:0,		//当前显示的页
	comboType:'selectcombo',//combo类型
    afterSetValue: Chenxin.emptyFn,
	extensionOp:Chenxin.emptyFn,//用于扩展类的相关操作
    setValue: function(newValue) {
        var oldValue = this.getValue();
		
		var v=newValue;
		if(typeof(newValue)=='string'){
			v=newValue.split(',');
		}
		if(!this._items){
			this.initValue=newValue;
			return;
		}
		// if(!this.items.length){
			// this.initValue=v;
		// }else{
			
		// }
		Chenxin.UI.Combo.superclass.setValue.call(this, v);		
        if (this.afterSetValue) {
            this.afterSetValue(newValue, oldValue);
        }
    },
    getValue: function() {
        if (this._val != undefined) {
            if (this.showMode == 'multi') {
				var v=this._val+'';
				return v.replace(this.defVal,'');
            }
            return this._val;
        } else {
            return "";
        }

    },
	getValueRecord:function(value){
		var json;
		var _v=value||this._val;
		
		if(_v) {
			if (this.showMode == 'multi'&&!value) {
				_v=','+_v+',';
				json=[];				
				for(var i=0;i<this.items.length;i++){
					if(_v.indexOf(','+this.items[i].val+',')!=-1){
						json.push(this.items[i]);
					}
				}
			
			}else{
				for(var i=0;i<this.items.length;i++){
					if(_v==this.items[i].val){
						json=this.items[i];
						break;
					}
				}
			}
			return json;
		}
		
		return {};

		
	},
	reset:function(){
		if(this.autoLoad||!this.actionUrl){
			this.setValue(this.defVal);
		}else{
			this.clearItems();
		}
	},
	resetValue:function(){
		this.setValue(this.defVal);
	},
    getText: function() {		
        if (this._txt != undefined) {
            if (this.showMode == 'multi') {
				var t=this._txt+'';
				return t.replace(this.defTxt,'');
            }
            return this._txt;
        } else {
            return "";
        }
       // return this._txt;
    },
    clearItems: function() {
        this.items = [];
        this.addPleaseSelected = true;
        $(this.containerId).empty();
        this.init();
    },
    setValeByText: function(txt) {
		var v='';
		if(this.showMode=='multi'){
			txt+=',';
			for (var i = 0; i < this.items.length; i++) {
				var t=this.items[i].txt+',';
				if (txt.indexOf(t)!=-1) {
					v+=this.items[i].val+',';
				}
			}
			if(v.length){
				v=v.substr(0,v.length-1);
			}
		}else{
			v=this.defVal;
			for (var i = 0; i < this.items.length; i++) {
				if (txt == this.items[i].txt) {
					v=this.items[i].val;
					break;
				}
			}		
		}
        this.setValue(v);
    },
    afterLoadItems: Chenxin.emptyFn,
    afterInit: Chenxin.emptyFn,
    setDisable: function() {
        this.disable = true;
		//已修改源代码
        // var containerId = this.containerId;
        // setTimeout(function() {
            // $(containerId).unbind();
        // }, 200);
    },
    setEnable: function() {
        this.disable = false;
		
		//已修改源代码
        //Chenxin.UI.Combo.superclass.refresh.call(this, this.items, this.getText(), this.getValue());
    },
    onSelected: function(obj) {//级联事件
    },
    loadItems: function(isInit, initVal) {
        var _this = this;
        Chenxin.ajax({
			type: "get",
			dataType: this.paramType,
			url: this.actionUrl,
			data: this.param,
			scope: this,
			onSuccess: function(data, msg) {
				if (data.items == undefined) {
					data.items = [];
				}
				this.items = data.items;
				if (this.afterLoadItems) {
					this.afterLoadItems(isInit,initVal);
				}
				this.handlerItems();
				if(this.extensionOp){//用户扩展类的处理操作
					this.extensionOp.call(this);
				}
				if (isInit) {//是否是初始化					
					this.init();
				} else {
					if (this.initValue!=undefined) {
						initVal = this.initValue;
						delete this.initValue;
					}
					if (!initVal) {
						Chenxin.UI.Combo.superclass.refresh.call(this, this.items, this.defTxt, this.defVal);
					} else {
						if (this.inModelType == 'txt') {
							Chenxin.UI.Combo.superclass.refresh.call(this, this.items, initVal, this.findValByTxt(initVal));
						} else {
							Chenxin.UI.Combo.superclass.refresh.call(this, this.items, this.findTxtByVal(initVal), initVal);
						}
					}
				}

				if (this.disable) {
					this.setDisable();
				}
			}
		});
    },
    findTxtByVal: function(val) {
		this._items=this.items;
        return Chenxin.UI.Combo.superclass.findTxtByVal.call(this, val);
    },
    findValByTxt: function(txt) {
        var val = '';
		txt=','+txt+',';
        for (var i = 0; i < this.items.length; i++) {
            if (txt.indexOf(','+this.items[i].txt+',')!=-1) {
				if(this.showMode=='multi'){				
					val +=','+this.items[i].val;
				}else{					
					val=this.items[i].val;
					break;
				}
            }
        }
		if(this.showMode=='multi'){
			return val.substr(1).split(',');
		}
        return val;
    },
    reload: function(initVal) {
        if (this.initValue) {
            this.loadItems(true);
        } else {
            this.loadItems(false, initVal);
        }
    },
    handlerItems: function() {
        if (this.addPleaseSelected) {
		
            if (!this.items.length) {
                this.items.unshift({ txt: this.defTxt, val: this.defVal });
            } else {
                if (this.items[0].txt != this.defTxt&&this.showMode!='multi') {
                    this.items.unshift({ txt: this.defTxt, val: this.defVal });
                }
            }
        }
    },
    init: function() {
        this.handlerItems();
        if (!this.name) {
            this.name = this.containerId.substring(1, this.containerId.length);
        }
        Chenxin.UI.Combo.superclass.initialize.call(this, this);
        if (!this.addPleaseSelected && this.items.length) {
            this.setValue(this.items[0].val);
        }

        if (this.initValue!=undefined) {//加载后的默认初始值设置，只是用一次，过时做法，此做法将触发afterSetVal事件
            if (this.inModelType == 'txt') {
                this.setValeByText(this.initValue);
            } else {
                this.setValue(this.initValue);
            }
            delete this.initValue;
        }

        if (this.afterInit) {
            this.afterInit();
        }
    },
    initValidator: function() {
		if(!$('#'+this.name+'Tip').length){
			$(this.containerId).after('<div id="' + this.name + 'Tip" style="float:left; margin-left: 5px; width: 50px; height: 26px; line-height: 26px; text-align: left; display:none" class="onError fl">请选择！</div>');		
		}
    },
    validator: function() {
        if (!this.required) {
			$('#' + this.name + 'Tip').hide();
            return true;
        }
		this.initValidator();
        if (this._val == this.defVal) {
            $('#' + this.name + 'Tip').show();
            return false;
        }
        $('#' + this.name + 'Tip').hide();
        return true;
    },
    initComponent: function() {
        if (this.autoLoad) {
            this.loadItems(true);
        } else {
            this.init();
        }
        if (this.disable) {
            this.setDisable();
        }
        if (this.required) {
            this.initValidator();
        }
    }
});

/**
*@description jqm窗体表单基类
*@extend null
*/
Chenxin.UI.FormCommon=Chenxin.extend(null,{
	id:'',
	autoCheckPermit:true,	//是否在弹出层的时候，自动检查权限
	alwaysCheckPermit:false,//是否一致调用权限检查方法，不过之前是否做过权限检查操作
	autoResetFormVal:true,	//是否在显示DIV层之前，重置表单验证状态
	comboList:[],
	actionUrl:'',
	autoHide:true,			//保存成功后是否自动隐藏弹出层，适用于type为"jqmodel"弹出层表单
	autoReset:true,			//保存成功后是否自动重置表单项，适用于type为"numal"非弹出层表单
	autoAlertSucc:true,		//保存成功后是否自动弹出保存成功的消息
	op:'add',
	renderTo:'',
	title:'添加',
	type:'jqmodel',//jqmodel为弹出式窗体，numal为普通页面的表单
	defBBtn:false,			//默认按钮，即『确定』和『取消』
	jqmHasFoot:true,		//弹出窗体是否显示底部部分
	scope:this,
	autoInit:true,
	formValConfig:{},
	winCls:'',
	disabled:false,
	additionalParam:{},
	jqmWidth:0,
	jqmHeight:0,
	permit:{},//权限
	permitParam:{},
	createComboList:Chenxin.emptyFn,
	/**
	*@description 在获取表单Json对象后，优化处理
	*@return null
	*/
	afterGetFormJson:Chenxin.emptyFn,
	/**
	*@description 将Json对象填充到表单之前处理
	*@return null
	*/
	beforeFitData:Chenxin.emptyFn,
	/**
	*@description 将Json对象填充到表单之后的处理
	*/
	afterFitData:Chenxin.emptyFn,
	/**
	*@description 显示之后，显示成功，权限检查等成功的调用方法
	*/
	afterShow:Chenxin.emptyFn,
	/**
	*@description 初始化表单验证，需重写
	*/		
	initFormValidator:Chenxin.emptyFn,
	saveSucc:Chenxin.emptyFn,
	saveFail:Chenxin.emptyFn,
	saveError:Chenxin.emptyFn,
	createForm:Chenxin.emptyFn,
	afterCheckPermit:Chenxin.emptyFn,//在执行权限检查获得结果后执行，参数为结果的data
	
	/**
	*@description 后台交互确认权限的方法
	*@name 作为code参数传递到后台的值
	*/
	checkPermit:function(name,param){
		if(this.permit[name+'_permit']!=undefined&&!this.alwaysCheckPermit){
			return;
		}
		Chenxin.Fn.checkPermit(this.actionUrl,name,function(data,msg){
			if(data.permit!=undefined){
				this.permit[name+'_permit']=data.permit;
				this.permit[name+'_pmsg']=msg;
			}
			
			if(this.afterCheckPermit){//附加执行的操作
				this.afterCheckPermit.call(this,data);
			}
		},this,param);
	},
	/**
	*@description 根据名称查找表单项，先查找input控件，再查找comboList
	*/
	findByName:function(name){
		if($('#'+this.id+' input[name="'+name+'"]').length){
			return $('#'+this.id+' input[name="'+name+'"]');
		}else if($('#'+this.id+' textarea[name="'+name+'"]').length){
			return $('#'+this.id+' textarea[name="'+name+'"]');
		}else{
			for(var i=0;i<this.comboList.length;i++){
				if(this.comboList[i].name==name){
					return this.comboList[i];
				}
			}
		}
		return $('#'+this.id+' input[name="'+name+'"]');
	},
	setDisable:function(){
		if(!this.disabled){
			this.disabled=true;
			if(this.type!='numal'&&this.jqmHasFoot){//新模式窗体
				this.jqWin.footDom.hide();
			}else{//兼容过去手动添加按钮的模式
				//$('#'+this.id+' tr:last').hide();			
			}
			Chenxin.Fn.setFormDisable(this.id,this.comboList);
		}else{
			Chenxin.Fn.setFormDisable('xxx',this.comboList);			
		}		
	},
	setEnable:function(){
		if(this.disabled){		
			this.disabled=false;
			if(this.type!='numal'&&this.jqmHasFoot){//新模式窗体
				this.jqWin.footDom.show();
			}else{//兼容过去手动添加按钮的模式
				//$('#'+this.id+' tr:last').show();			
			}
			Chenxin.Fn.setFormEnable(this.id,this.comboList);
		}
	},
	getParam:function(){
		var json=Chenxin.Fn.getFormJson(this.id,this.comboList);		
		if(this.afterGetFormJson){
			var scope=this.scope
			if(this.scope==window){
				scope=this;
			}
			this.afterGetFormJson.call(scope,json);			
		}
		return json;
	},
	fitData:function(model,notAutoInit){
		if(model){
			var scope=this.scope
			if(this.scope==window){
				scope=this;
			}
			if(this.beforeFitData){
				this.beforeFitData.call(scope,model);
			}
			Chenxin.Fn.setFormValue(this.id,this.comboList,model,notAutoInit);
			if(this.afterFitData){
				this.afterFitData.call(scope,model);
			}
		}	
	},
	initJqm:function(selector){
		if(!selector){
			selector='#'+this.id;
		}
		$(selector).jqm({ trigger: false}).jqDrag('.jqDrag');
	},	
	reset:function(){
		this.fitData({});
	},
	resetFormVal:function(){
	    if (this.autoResetFormVal && this.initFormValidator) {
			try{
				jQuery.formValidator.resetTipState(this.id);
			}catch(e){
				alert('此表单没有添加表单验证！');
			}			
		}
	},	
	/**
	*@description 显示弹出层,默认执行权限检查，弹出成功，返回true,否则返回false
	*@permitCode 传递到后台的code，默认为this.op
	*@permitParam 传递到后台的检查权限的其他参数，默认为this.permitParam
	*/
	show:function(permitCode,permitParam){
		if(this.type=='numal'){
			return;
		}
	
		if(this.autoCheckPermit){	
			var code=permitCode||this.op;
			this.checkPermit(code,permitParam||this.permitParam);
			if(!this.permit[code+'_permit']){
				alert(this.permit[code+'_pmsg']||'您无该权限，请与管理员联系！');
				return false;
			}else{
				if(!this.jqWin){
					this.init();
				}
				this.jqWin.show();
				this.resetFormVal();
				if(this.afterShow){
					this.afterShow();
				}
				return true;
			}
		}else{			
			if(!this.jqWin){
				this.init();
			}
			this.jqWin.show();
			this.resetFormVal();
			if(this.afterShow){
				this.afterShow();
			}
			return true;
		}
	},
	hide:function(){
		if(this.type!='numal'){
			this.jqWin.hide();
		}
		
	},
	checkCombo:function(){
		var count=0;
		for(var i=0;i<this.comboList.length;i++){
			if(!this.comboList[i].validator()){
				count++;
			}
		}
		if(count){
			return false;
		}
		return true;
	},
	formValidator:function(model){
		if(this.initFormValidator){		
			if(!jQuery.formValidator.pageIsValid(this.id)||!this.checkCombo()){
				alert('请填写完必填(选)项再进行表单提交！');
				return false;
			}
		}else{
			if(!this.checkCombo()){
				alert('请填写完必填(选)项再进行表单提交！');
				return false;
			}
		}
		if(this.customerFormVal){
			return this.customerFormVal(model);
		}
		return true;
	},
	save:function(url){
		if(this.disabled){
			alert('当前不可提交数据！');
			return;
		}
		Chenxin.Msg.Saving.show();
		var model=this.getParam();
		if(!this.formValidator(model)){	
			Chenxin.Msg.Saving.hide();
			return;
		}
		var _data={
			op:this.op
		};		
		var m=model.toString();
		if(m!='{}'){			
			_data.model=m;
		}
		
		Chenxin.apply(_data,this.additionalParam);
		var _this=this;
		Chenxin.ajax({
			type: "post",
			dataType: "json",
			url: url||this.actionUrl,
			data: _data,
			onSuccess: function(data,msg) {	
				Chenxin.Msg.Saving.hide();
				
				if(_this.autoAlertSucc){
					alert(msg);
				}		
				if(_this.saveSucc){		
					_this.saveSucc.call(_this.scope,data,msg);
				}
				if(_this.type=='jqmodel'){
					if(_this.autoHide){
						_this.hide.call(_this);
					}
				}else{
					if(_this.autoReset){
						_this.reset.call(_this);
						_this.resetFormVal.call(_this);		
					}
				}				
			},
			onFail:function(data,msg){
				Chenxin.Msg.Saving.hide();	
				if(_this.saveFail){
					_this.saveFail(_this.scope,data,msg);
				}					
			},
			onError:function(){
				Chenxin.Msg.Saving.hide();	
				if(_this.saveError){
					_this.saveError(_this.scope);
				}		
			}
		});
	},
	setTitle:function(title){
		this.jqWin.setTitle(title);
		//$('#'+this.id+' .jqmTitle span[class="title"]').text(title);
	},
	setWidth:function(width){
		if(!width){
			return;
		}
		this.jqWin.setWidth(width);
		$('#'+this.id).css('width',width+'px');
	},
	del:function(modelid,op,confirmMsg){	
		var _this=this;
		
        if (confirm(confirmMsg||'确定要删除该条记录吗？')){
			Chenxin.ajax({				
				type: "get",
				dataType: "json",
				url: this.actionUrl+(this.actionUrl.indexOf('?')==-1?'?':'&')+'modelid='+modelid,
				data: {op:op||'del'},
				onSuccess: function(data,msg) {
					if(_this.autoAlertSucc){
						alert(msg);
					}
					if(_this.type=='jqmodel'){
						if(_this.autoHide){
							_this.hide.call(_this);
						}
					}else{
						if(_this.autoReset){
							_this.reset.call(_this);
						}
					}
					if(_this.afterDelSucc){
						_this.afterDelSucc.call(_this.scope,data);
					}
				}
			});
		}
	},
	initEvent:Chenxin.emptyFn,
	/**
	*@description 自定义表单验证，在formValidator验证通过后和DIV下拉Combo验证通过后执行，可重写
	*/
	customerFormVal:Chenxin.emptyFn,
	createBBtn:Chenxin.emptyFn,
	init:function(){
		if(this.type=='jqmodel'){
			//this.jqWin=Chenxin.Fn.createJQWin(Chenxin.Fn.createJQTitle(this.title)+this.createForm(),this.id,this.winCls,this.jqmWidth);
			//document.getElementById(this.renderTo).innerHTML=this.jqWin;
			
			//this.initJqm();
			var _this=this;
			
			
			this.jqWin=new Chenxin.UI.Win({
				id:this.id,
				width:parseInt(_this.jqmWidth),
				title:this.title,
				hasFoot:_this.jqmHasFoot,
				height:_this.jqmHeight,
				content:this.createForm(),
				createBtn:function(){
					if(_this.defBBtn){
						return [{
							text:'确定',
							handler:_this.save,
							scope:_this
						},{
							text:'取消',
							handler:this.hide
						}]					
					}else{
						if(_this.createBBtn){
							return _this.createBBtn.call(_this);
						}
					}
					if(this.footDom){
						this.footDom.hide();
					}
					return [];
				}
			});
		}
		
		if(this.createComboList){
			this.comboList=this.createComboList();
		}		
		if(this.initFormValidator){
			this.initFormValidator();
		}
		if(this.initEvent){
			this.initEvent();
		}	
	},
	initComponent:function(){
		if(!this.id){
			throw new Error('id is need!');
			return; 
		}
		var _this=this;
		if(this.initFormValidator){		
			Chenxin.apply(this.formValConfig,{onsuccess:function(){	
				return true;
			},validatorgroup:this.id});
			jQuery.formValidator.initConfig(this.formValConfig);
		}
		if(this.autoInit){
			this.init();
		}
		this.permit={};
	}
});
/**
*@description 查询面板父类
*@extend null
*/
Chenxin.UI.SearchCommon=Chenxin.extend(null,{
	comboList:[],
	scope:this,
	autoReload:true,//是否在点击查询按钮后，重新加载列表，可以在afterGetParamJson方法中，加入必要的业务逻辑判断，控制该属性
	id:'',
	afterGetParamJson:Chenxin.emptyFn,
	createComboList:Chenxin.emptyFn,
	initEvent:Chenxin.emptyFn,
	getParamJson:function(){
		var json=Chenxin.Fn.getFormJson(this.id,this.comboList);
		if(this.afterGetParamJson){
			this.afterGetParamJson(json);
		}
		return json;
	},	
	reset:function(){
		Chenxin.Fn.setFormValue(this.id,this.comboList);
	},
	initComponent:function(){
		if(this.createComboList){
			this.comboList=this.createComboList();
		}
		if(this.initEvent){
			this.initEvent();
		}
	}
});

/**
*@description 页面基类
*@extend null
*/
Chenxin.UI.PageCommon=Chenxin.extend(null,{	
	actionUrl:'',
	/**
	*@description 当前记录ID
	*/	
	currentId:'',
	/**
	*@description 权限集合
	*/
	permit:{},
	/**
	*@description 是否自动加载列表数据
	*/	
	autoLoadGrid:true,
		
	/**
	*@description 添加，弹出添加DIV
	*/
	add:function(op){
		this.form.op=op||'add';
		if(this.form.show()){		
			if(this.form.disabled){
				this.form.setEnable();
			}
		}
	},
	/**
	*@description Ajax交互，对选中记录进行删除
	*/
	del:function(op,confirmMsg,url,param,check){//删除操作
		check=check||this.currentId;
		
		if(!check){
			alert('请选择一条记录！');
			return;
		}
	
		var _this=this;
		param=param||{};
		Chenxin.applyIf(param,{op:op||'del',modelid:this.currentId});
        if (confirm(confirmMsg||'确定要删除该条记录吗？')){
			Chenxin.ajax({				
				type: "get",
				dataType: "json",
				url: url||this.actionUrl,
				data: param,
				onSuccess: function(data,msg) {
					alert(msg);
					if(_this.grid){
						_this.grid.reload();
					}
					if(_this.afterDelSucc){
						_this.afterDelSucc.call(_this,data,msg);
					}
				}
			});
		}			
	},
	delList:function(){
		if(this.grid&&this.grid.getSelectList){
			var idList=this.grid.getSelectList();
			this.del('','确定删除这几条记录吗？','',{modelid:idList},idList);
		}
	},
	
	/**
	*@description Ajax交互，根据modelid，获取Model实体JSON
	*@modelId modelId
	*@callBack 回调函数
	*/
	getModel:function(modelId,callBack,scope,url,op,data){
		Chenxin.Msg.Waiting.show();		
		var _this=this;
		data=data||{};
		Chenxin.apply(data,{op:op||'getmodel',modelid:modelId});
		Chenxin.ajax({
			type: "post",
			dataType: "json",
			url: url||this.actionUrl,
			data: data,
			onSuccess: function(data) {
				_this.currentModel=data.model;
				callBack.call(scope,data.model);
				if(_this.afterGetModel){
					_this.afterGetModel.call(_this,data.model);
				}
				Chenxin.Msg.Waiting.hide();
			},
			onFail:function(data){
				Chenxin.Msg.Waiting.hide();	
				
				if(scope){
					if(scope.hide){
						scope.hide();
					}
				}
					
			},
			onError:function(){
				Chenxin.Msg.Waiting.hide();
				
				if(scope){
					if(scope.hide){
						scope.hide();
					}
				}
			}
		});
	},
	
	/**
	*@description 查看，表单项不可编辑
	*/
	view:function(){		
		this.form.op='view';
		if(this.form.show()){
			this.getModel(this.currentId,this.form.fitData,this.form);
			this.form.setDisable();		
		}
	},
	
	/**
	*@description 编辑，弹出层，加载Model数据
	*/
	edit:function(){
		if(!this.currentId){
			alert('请先选择一条记录！');
		}else{
			this.form.op='edit';
			if(this.form.show()){			
				if(this.form.disabled){
					this.form.setEnable();
				}
				this.getModel(this.currentId,this.form.fitData,this.form);	
			}		
		}
	},

	/**
	*@description 导出数据
	*/
	exportData:function(){
		if(this.grid){		
			//执行权限检查
			if(this.permit.exportdata_permit==undefined){			
				Chenxin.Fn.checkPermit(this.actionUrl,'exportdata',function(data,msg){
					if(data.permit!=undefined){
						this.permit.exportdata_permit=data.permit;	
					}
				},this);
			}
			
			if(this.permit.exportdata_permit){			
				this.grid.exportData();
			}else{
				alert('您没有此权限，请联系管理员！');
			}
		}else{
			alert('数据导出失败，没有数据列表');
		}
	},
	
	/**
	*@description 创建Grid,暂用，需进一步封装
	*/
	createGrid:Chenxin.emptyFn,	
	
	/**
	*@description 创建Form，即JQWin,暂用，需进一步封装
	*/
	createForm:Chenxin.emptyFn,	
	
	/**
	*@description 创建Grid,暂用，需进一步封装
	*/
	createSearch:Chenxin.emptyFn,	
	
	/**
	*@description 初始化页面元素事件处理，需重写
	*/
	initEvent:Chenxin.emptyFn,
		
	/**
	*@description 用户自定义页面初始化方法
	*/
	customerInit:Chenxin.emptyFn,
	
	/**
	*@description 在GetModel成功后，调用的方法
	*/
	afterGetModel:Chenxin.emptyFn,
	
	/**
	*@description 查询
	*/
	reloadGrid:function(searchModel,pageIndex){
		if(!searchModel){
			if(this.search){
				searchModel=this.search.getParamJson();
			}
			if(this.search.autoReload){//在search的AfterGetFormJson中控制该属性，判断必要的业务逻辑
				this.grid.reload(searchModel,pageIndex);
			}else{
				return;
			}
		}else{
			this.grid.reload(searchModel,pageIndex);
		}
		//this.grid.reload(searchModel || this.search.getParamJson());
		if(this.currentId){
			delete this.currentId;
		}
		if(this.currentModel){
			delete this.currentModel;
		}
	},
	/**
	*@description 搜索按钮专用，回到第一页
	*/
	searchGrid:function(){
		this.reloadGrid('',0);
	},
	/**
	*@description 类初始化方法，初始化页面元素事件处理，创建Grid，初始化表单
	*/		
	initComponent:function(){
		
		//创建查询
		if(this.createSearch){
			this.search=this.createSearch();
		}
		
		//创建表格
		if(this.createGrid){
			this.grid=this.createGrid();		
		}
		
		//创建表单
		if(this.createForm){
			this.form=this.createForm();
		}
		
		if(this.customerInit){
			this.customerInit();
		}
		
		//绑定元素页面事件
		if(this.initEvent){
			this.initEvent();		
		}	
		
	}
});

/**
*@description 数据字典下拉框封装
*/
Chenxin.UI.ParameterCombo=Chenxin.extend(Chenxin.UI.Combo,{
	actionUrl:'/service/selector.ashx',
	typeModel:'new',
	key:'',
	autoLoad:true,
	reload:function(initVal){
		this.actionUrl=this.initUrl+'?key='+this.key+'&type=datadic';
		Chenxin.UI.ParameterCombo.superclass.reload.call(this,initVal);
	},
	initComponent:function(){
		if(Chenxin.data.dictionary&&Chenxin.data.dictionary[this.key.replace('.','')]){
			this.items=Chenxin.data.dictionary[this.key.replace('.','')];
			this.autoLoad=false;
			this.actionUrl='';
		}else{
			this.initUrl=this.actionUrl;
			this.actionUrl+='?key='+this.key+'&type=datadic';
		}
		
		Chenxin.UI.ParameterCombo.superclass.initComponent.call(this);
	}
});

/**
*@description 组织结构下拉框封装
*/
Chenxin.UI.StructCombo = Chenxin.extend(Chenxin.UI.Combo, {
    actionUrl: '/service/structhandler.ashx',
    typeModel: 'new',
    autoLoad: true,
    reload: function(initVal) {
        if (this.param.fatherid && Chenxin.data.struct.map[this.param.fatherid + '_' + this.param.op]) {
            this.items = Chenxin.data.struct.store[Chenxin.data.struct.map[this.param.fatherid + '_' + this.param.op].index];
            if (!initVal) {
                Chenxin.UI.Combo.superclass.refresh.call(this, this.items, this.defTxt, this.defVal);
            } else {
                if (this.inModelType == 'txt') {
                    Chenxin.UI.Combo.superclass.refresh.call(this, this.items, initVal, this.findValByTxt(initVal));
                } else {
                    Chenxin.UI.Combo.superclass.refresh.call(this, this.items, this.findTxtByVal(initVal), initVal);
                }
            }
            return;
        }
        Chenxin.UI.StructCombo.superclass.reload.call(this, initVal);
    },
    extensionOp: function() {//扩展处理，保存items
        if (!Chenxin.data.struct.map[this.param.fatherid + '_' + this.param.op]) {
            Chenxin.data.struct.store.push(this.items);
            Chenxin.data.struct.map[this.param.fatherid + '_' + this.param.op] = { index: Chenxin.data.struct.store.length - 1 };
        }
    },
    initComponent: function() {
        if (this.param.op == 'getcity') {
            if (Chenxin.data.struct.map.city) {
                this.autoLoad = false;
                this.items = Chenxin.data.struct.store[Chenxin.data.struct.map.city.index];
            }
        }
        Chenxin.UI.StructCombo.superclass.initComponent.call(this);
    }
});

/**
*@description 最近10年的Combo
*/
Chenxin.UI.LastYearCombo=Chenxin.extend(Chenxin.UI.Combo,{
	actionUrl:'/service/common.ashx?op=getlastyearcombo',
	yearLength:10,
	autoLoad:true,
	initComponent:function(){
		this.param={yearlength:this.yearLength};
		Chenxin.UI.LastYearCombo.superclass.initComponent.call(this);	
	}
});

/**
*@description 最近10年的Combo
*/
Chenxin.UI.BuildingYearCombo=Chenxin.extend(Chenxin.UI.Combo,{
	containerId:'#community_CompleteYear',
	name:'CompleteYear',
	colNum:4,
	initComponent:function(){
		this.items=comboCommon.buildingYear();
		Chenxin.UI.BuildingYearCombo.superclass.initComponent.call(this);	
	}
});

/**
*@description 分页 AJAX返回数据格式：{success:'1',msg}
*@param domId放置内容的ID，必配置
*@param actionUrl执行AJAX操作后去后台数据的地址，必配置,注意：固定参数建议最佳在actionUrl后
		例如：service/a.ashx?op='getlist'，否则在reload的时候，isReplace为true，会冲掉该参数
*@param data执行AJAX操作传递到后台的数据
*/
Chenxin.UI.Pagination=Chenxin.extend(null,{
	actionUrl:'',
	id:'',
	domId:'',//此属性已经废弃
	type: "get",
	renderTo:'',
	dataType: "text",
	data:{},
	baseParam:{},
	recordCount:0,
	pageSize:50,
	pageIndex:0,
	minHeight:0,
	width:0,
	autoLoad:true,
	expertFileName:'数据导出',
	autoShowLoading:true,//是否在后台获取列表数据时，自动弹出Loading进度
	/**
	*@description 用AJAX获得后台数据后，进行页面渲染
	*/
	render:Chenxin.emptyFn,
	/**
	*@description 是否需要AJAX获取Count
	*/
	isLoadCount:true,
	clear:function(){
		$('#'+this.renderTo).text('');
		$('#'+this.id+'_pagebar').text('');		
	},
	exportData:function(){
		Chenxin.Fn.exportToExcel(document.getElementById(this.renderTo).innerHTML,this.expertFileName);
	},
	load:function(pageIndex,isCallBack){	
		if(this.hasCount&&isCallBack){
			this.hasCount=false;
			return;
		}	
		if(this.autoShowLoading){
			Chenxin.Msg.Loading.show();		
		}
		this.pageIndex=pageIndex;
		
		//将基础参数添加进去
		Chenxin.apply(this.data,this.baseParam);
		
		Chenxin.ajax({ 
			type: this.type,
			dataType: this.dataType,
			url: this.actionUrl+(this.actionUrl.indexOf('?')!=-1?'&':'?')+'pageindex='+pageIndex+'&pagesize='+this.pageSize,
			data: this.data,
			scope:this,
			onSuccess: function(data,msg) {	
				if(data.count!=undefined){					
					this.recordCount=parseInt(data.count);
				}
				if(this.renderTo){
					$('#'+this.renderTo).css('overflow','auto');
					var width=$($('#'+this.renderTo)[0].parentNode).css('width');
					if(this.width){					
						$('#'+this.renderTo).css('width',this.width+'px');
					}else{					
						$('#'+this.renderTo).css('width',width);
					}
					
					if(this.minHeight){
						$('#'+this.renderTo).css('min-height',(this.minHeight-30)+'px');
					}
					document.getElementById(this.renderTo).innerHTML=data.data;
					if(!$('#'+this.id+'_pagebar').length){
						$('#'+this.renderTo).after('<div style="width:'+(this.width?(this.width+'px'):(width))+';" id="'+this.id+'_pagebar"></div>');
					}else{
						if(!this.recordCount){						
							$('#'+this.id+'_pagebar').text('');
						}
					}
					if(this.afterRender){
						this.afterRender(data,msg);
					}					
				}else{
					if(this.render){//如果
						this.render.call(this,data.data);
					}
				}
				
				if(this.isLoadCount&&!isCallBack){//需要ajax获取count之后，执行分页	
					this.hasCount=true;
					this.createPagination();
				}
				if(this.autoShowLoading){
					Chenxin.Msg.Loading.hide();				
				}
			},
			onWrong:function(){
				if(this.autoShowLoading){
					Chenxin.Msg.Loading.hide();				
				}							
			},
			onFail:function(){
				if(this.autoShowLoading){
					Chenxin.Msg.Loading.hide();				
				}				
			},
			onError:function(){				
				if(this.autoShowLoading){
					Chenxin.Msg.Loading.hide();				
				}
			}
		});
	},
	createPagination:function(){
		if(this.id||this.domId||this.renderTo){
			var _this=this;
			var _opt={
				items_per_page: this.pageSize,
				containerId:'#'+this.id+'_pagebar',
				//renderTo:'#'+this.renderTo+',',
				callback:function(pageIndex, jq){
					_this.load(pageIndex,true);
				}
			};		
			if(this.id){
				$("#"+this.id+'_pagebar').pagination(this.recordCount,_opt);
			}else{
				$('#'+this.domId).text('');
				$("#"+this.domId).pagination(this.recordCount,_opt);				
			}
		}
	},
	
	/**
	*@description 重新加载，根据新的参数
	*@param 查询参数，object 例如：{a:'1'}
	*@isCover 是否将@param覆盖当前this.data的参数，true覆盖，直接替换
	*/
	reload:function(param,isCover,currentPageIndex){
		if(param){
			if(!isCover){
				this.data=param;
			}else{
				Chenxin.apply(this.data,param);			
			}
		}
		this.init(currentPageIndex);
	},
	init:function(currentPageIndex){	
		if(this.isLoadCount){//此情况为没有count，需要执行load方法，获取得count,并获取第一页的列表数据，如果有
			//避免两次加载第一页分页数据
			this.hasCount=false;
			if(!currentPageIndex){
				this.load(0,false);			
			}else{		
				this.load(this.pageIndex,false);
			}
			
		}else{//此情况为有count，列表数据有分页的回调函数去获取
			this.createPagination();
		}
	},
	initComponent:function(){
		if(!this.id){
			this.id=this.renderTo;
		}
		if(this.autoLoad){
			this.init();
		}
	}	
});

Chenxin.UI.PageBar=Chenxin.extend(null,{
	scope:this,
	pageSize:20,
	pageIndex:0,
	totalRecord:0,
	pagingCb:Chenxin.emptyFn,//分页按钮点击后的回调函数，通常执行重新加载数据
	getPageCount:function(){
		return parseInt(this.totalRecord/this.pageSize)+(this.totalRecord%this.pageSize==0?0:1);
	},
	createBtn:function(name,title,cls){
		var _t=document.createElement('input');
		_t.name=name;
		_t.title=title;
		_t.className=cls;
		_t.type='button';
		
		return $(_t);
	},
	init:function(){		
		var _p=document.createElement('div');
		_p.className=this.pageCls||'x-page';
		this.el=$(_p);
		
		
		//添加分页工具条
		var t=document.createElement('table');
		$(t).appendTo(this.el);
		var tr=document.createElement('tr');
		$(tr).appendTo(t);
		
		//总记录数显示
		var countTd=document.createElement('td');
		countTd.style.padding="0px 5px;";
		this.countDom=$(countTd);
		this.countDom.appendTo($(tr));
		
		var cls='';
		
		//first
		this.firstBtn=this.createBtn('btn_first','首页','x-page-first-disable');
		$(tr).append($(document.createElement('td')).append(this.firstBtn));
		
		//prev
		this.prevBtn=this.createBtn('btn_prev','上一页','x-page-prev-disable');
		$(tr).append($(document.createElement('td')).append(this.prevBtn));
		
		//separator
		$(tr).append($(document.createElement('td')).addClass('x-separator'));
		
		//分页统计
		var pageIndexTbx=document.createElement('input');
		pageIndexTbx.type='text';
		pageIndexTbx.className='x-page-index-input';
		pageIndexTbx.value=this.pageIndex+1;
		this.pageTbx=$(pageIndexTbx);
		var mTd=document.createElement('td');
		mTd.innerHTML='第';
		$(mTd).append(this.pageTbx);
		$(mTd).append('页 / 共');
		this.totalSpn=$(document.createElement('span'));
		this.totalSpn.css('color','#003399');
		this.totalSpn.text(this.totalRecord);
		$(mTd).append(this.totalSpn);			
		$(mTd).append('页');
		$(tr).append(mTd);
		
		//separator
		$(tr).append($(document.createElement('td')).addClass('x-separator'));
		
		
		//next
		this.nextBtn=this.createBtn('btn_next','下一页','x-page-next-disable');
		$(tr).append($(document.createElement('td')).append(this.nextBtn));
		
		//next
		this.lastBtn=this.createBtn('btn_last','尾页','x-page-last-disable');
		$(tr).append($(document.createElement('td')).append(this.lastBtn));
		
		var _this=this;
		
		this.firstBtn.bind('click',function(e){				
			if(this.className=='x-page-first-disable'){
				return;
			}
			_this.pageIndex=0;
			_this.paging();
		});
		this.prevBtn.bind('click',function(e){				
			if(this.className=='x-page-prev-disable'){
				return;
			}		
			_this.pageIndex-=1;
			_this.paging();
		});
		this.nextBtn.bind('click',function(e){	
			if(this.className=='x-page-next-disable'){
				return;
			}	
			
			_this.pageIndex+=1;
			_this.paging();
		});
		this.lastBtn.bind('click',function(e){				
			if(this.className=='x-page-last-disable'){
				return;
			}
			_this.pageIndex=_this.getPageCount()-1;	
			_this.paging();
		});
		
		this.pageTbx.bind('keydown',function(e){
			if(e.keyCode==13||(e.keyCode>45&&e.keyCode<58)||e.keyCode==8||(e.keyCode>95&&e.keyCode<106)){
				if(e.keyCode==13){
					if(!this.value){
						return;
					}
					var length=_this.getPageCount();
					var _c=parseInt(this.value)
					if(_c>length||_c<1){
						return;
					}else{		
						_this.pageIndex=_c-1;
						_this.paging();
					}
				}
			}else{
				return false;
			}
		});
	},
	paging:function(){
		this.scope.pageIndex=this.pageIndex;
		if(this.pagingCb){
			this.pagingCb.call(this.scope);
		}
	},
	reRender:function(total){
		if(total!=undefined){
			this.totalRecord=total;
		}
		this.countDom.html('共<span style="color:#003399;">'+this.totalRecord+'</span>条记录 每页<span style="color:#003399;">'+this.pageSize+'</span>条 ');
		var length=this.getPageCount();
		this.totalSpn.text(length);
		this.pageTbx.val(this.pageIndex+1);
		
		
		this.firstBtn.removeClass();
		this.prevBtn.removeClass();
		this.nextBtn.removeClass();
		this.lastBtn.removeClass();
		
		
		if(length==1||length==0){
			this.firstBtn.addClass('x-page-first-disable');
			this.prevBtn.addClass('x-page-prev-disable');	
			this.nextBtn.addClass('x-page-next-disable');
			this.lastBtn.addClass('x-page-last-disable');	
		}else{
			switch(this.pageIndex){
				case 0:
					this.firstBtn.addClass('x-page-first-disable');
					this.prevBtn.addClass('x-page-prev-disable');
					if(this.pageIndex==length-1){				
						this.nextBtn.addClass('x-page-next-disable');
						this.lastBtn.addClass('x-page-last-disable');	
					}
					this.nextBtn.addClass('x-page-next');
					this.lastBtn.addClass('x-page-last');
					break;
				case length-1:
					this.firstBtn.addClass('x-page-first');
					this.prevBtn.addClass('x-page-prev');
					this.nextBtn.addClass('x-page-next-disable');
					this.lastBtn.addClass('x-page-last-disable');							
					break;
				default:
					this.firstBtn.addClass('x-page-first');
					this.prevBtn.addClass('x-page-prev');
					this.nextBtn.addClass('x-page-next');
					this.lastBtn.addClass('x-page-last');
					break;
			}
		}
		
	},
	initComponent:function(){
		if(!this.renderTo){
			throw new Error('renderTo is need!')
		}
		this.init();
		if(typeof(this.renderTo)=='string'){
			$('#'+this.renderTo).append(this.el);
		}else{
			this.renderTo.append(this.el);
		}
		//this.scope.el.after(this.el);
	}
});

Chenxin.UI.BaseGrid=Chenxin.extend(null,{
	actionUrl:'',
	addRowHoverCls:true,			//添加行鼠标滑过样式
    param: {}, 						//查询参数
    baseParam: {}, 					//基础参数，不发生变化的参数，可以手动进行修改
    autoLoad: true, 				//是否自动加载数据
    gridCls: 'x-grid-main', 		//表格样式
    selectCls: 'x-grid-select', 	//行选中样式
    hoverCls: 'x-grid-hover', 		//行滑过样式
    pageCls: 'x-grid-page', 		//分页工具条样式
	rowCls:'x-grid-row',			//行样式
	footCls:'x-grid-foot',			//注脚
	titleCls:'x-grid-title',		//标题样式
	titleIcon:'x-grid-title-icon',	//标题Icon
    height:0, 						//高度
    width: 0, 						//宽度
    gridWidth: 0, 					//内嵌数据table宽度
    hasPage: true, 					//有分页
    pageIndex: 0, 					//当前页码
    pageSize: 50, 					//当前每页显示的记录条数
	count:0,
    sortField: '', 					//排序字段
    id: '', 						//ID
    renderTo: '', 					//渲染的容器   
	title:'数据列表',						//标题
	hasTitle:true,
	collapsible:false,				//是否可以收起
	exportAble:true,				//是否可以导出
	collapsedCls:'x-grid-collapse',	//收起按钮样式
	expandCls:'x-grid-expand',		//点开按钮样式
	exportCls:'x-grid-export',		//导出按钮样式
	animation:true,					//收起展开动画
    scope: this,
	expertFileName:'数据导出',	
	exportData:function(){		
		Chenxin.Fn.exportToExcel(this.mainDom.html(),this.expertFileName);
	},
	clear:function(){		
		this.mainDom.empty();
	},
	createPage: function() {
        if (this.hasPage) {
            if (!this.pageBar) {
                this.pageBar = new Chenxin.UI.PageBar({
                    scope: this,
					renderTo:this.footDom,
                    pageSize: this.pageSize,
                    pageIndex: this.pageIndex,
                    pagingCb: function() {
                        this.reload();
                    }
                });
            }
        }
    },
	load: function() {
        Chenxin.Msg.Loading.show();
        var _data = {};
        Chenxin.apply(_data, this.param);
        Chenxin.apply(_data, this.baseParam);
        _data.sort = this.sortField;
        if (this.hasPage) {
            _data.pageindex = this.pageIndex;
            _data.pagesize = this.pageSize;
        }

        var _this = this;
        Chenxin.ajax({
            type: 'get',
            dataType: 'html',
            url: this.actionUrl,
            data: _data,
            onSuccess: function(data, msg) {
				_this.count=data.count;
                Chenxin.Msg.Loading.hide();
				
		
				// f=function(config){
					// config.scope.render.call(config.scope,config.data);
				// }
                if (_this.render) {
					_this.render.call(_this,data);
					// Concurrent.Thread.create(f,{scope:_this,data:data});
                }
				
                if (_this.afterRender) {
                    _this.afterRender.call(_this, data, msg);
                }
            },
            onWrong: function() {
                Chenxin.Msg.Loading.hide();
            },
            onFail: function() {
                Chenxin.Msg.Loading.hide();
            },
            onError: function() {
                Chenxin.Msg.Loading.hide();
            }
        });
    },
    reload: function(param,pageIndex) {
        this.param = param || this.param;
        this.clear();
		if(pageIndex!=undefined&&pageIndex>-1){
			this.pageIndex=pageIndex;
			if(this.pageBar){
				this.pageBar.pageIndex=this.pageIndex;
			}
		}
        this.load();
    },
	createTitleTool:Chenxin.emptyFn,
	afterRenderTitleTool:Chenxin.emptyFn,
	/**
	*@description 根据配置，生成按钮
	*/
	initButton:function(btnConfig,renderDom){
		if(btnConfig){
			if(typeof(renderDom)=='string'){
				renderDom=$('#'+renderDom);
			}
			for(var i=btnConfig.length-1;i>=0;i--){//var i=0;i<btnConfig.length;i++)
				var t=document.createElement('span');
				t.id=btnConfig[i].id||'';
				if(btnConfig[i].cls){
					t.className='x-grid-title-btn '+btnConfig[i].cls;
				}else{
					t.className='x-grid-title-btn'				
				}
				if(btnConfig[i].showTitle!=false){
					t.title=btnConfig[i].title||btnConfig[i].text;				
				}
				t.innerHTML=btnConfig[i].text;
				btnConfig[i].scope=btnConfig[i].scope||this;
				
				var f=btnConfig[i].handler;
				if(f){				
					$(t).bind('click',{fn:btnConfig[i].handler,scope:btnConfig[i].scope||this},function(e){
						e.data.fn.call(e.data.scope,this,e);//f.call(btnConfig.scope,this);
					});
				}
				renderDom.append(t);
			}
		}
	},
	createDom:function(cls,content){
		var _d=document.createElement('div');
		if(cls){
			_d.className=cls;		
		}
		if(content){
			_d.innerHTML=content;
		}
		return $(_d);
	},
	createTitleDom:function(){	
		return this.createDom(this.titleCls||'x-grid-title','<span class="'+this.titleIcon+'">'+this.title+'</span>');
	},
	createMainDom:function(){
		return this.createDom(this.gridCls||'x-grid-main');
	},
	createFootDom:function(){
		return this.createDom(this.footCls||'x-grid-foot');
	},
	createCollapseBtn:function(){	
		if(this.collapsible&&this.titleDom){
			this.titleDom.append('<span id="collapse_'+this.renderTo+'" class="'+this.collapsedCls+'" title="收起"></span>');
		}
	},
	createExportBtn:function(){
		if(this.exportAble&&this.titleDom){
			this.titleDom.append('<span id="export_'+this.renderTo+'" class="'+this.exportCls+'" title="导出列表">导出</span>');
		}
	},
	render:function(data){
		this.mainDom.append(data.html||data.data);
		this.mainDom.slideDown();
		this.resetRowCls(this.mainDom);
		this.resetPageBar(data);
	},
	resetPageBar:function(data){
        if (this.hasPage) {
            this.pageBar.reRender(data.count);
        }		
	},
	resetRowCls:function(dom){	
		var _obj=this;
		dom.find('tr').each(function(i){
			if(i%2==1){//奇数行，添加样式，从0开始
				$(this).addClass('x-grid-row-odd');
			}
			$(this).addClass(_obj.rowCls);
		});
	},
	setTitle:function(title){
		title=title||this.title;
		if(title!=this.title&&this.titleDom){
			this.titleDom.children().eq(0).text(title);
			this.title=title;
		}
	},
	getTitle:function(){
		return this.title;
	},
	init: function() {
		this.titleDom=this.createTitleDom();
		if(!this.hasTitle){
			this.titleDom.css('display','none');
		}
		this.el.append(this.titleDom);
		
		this.mainDom=this.createMainDom();
		if(!this.hasPage){
			this.mainDom.css('border-bottom-width','1px');
		}
		this.el.append(this.mainDom);
		
		this.footDom=this.createFootDom();
		this.el.append(this.footDom);
		
		this.createPage();
		
		
		this.el.addClass('x-grid-dom');
		
		this.createCollapseBtn();
		this.createExportBtn();
		
    },
	setSize:function(){		
		if(this.width){
			this.el.css('width',this.width+'px');
		}
		if(this.height){
			this.mainDom.height(this.height);
		}
	},
	checkIsRowSelect:function(e){		
		if (e.target.tagName != 'TD') {
			return false;
		}
		return true;
	},
	initEvent: function() {
        var _obj = this;
        var _tr =$('.'+this.rowCls);
		
		if(this.addRowHoverCls){
			_tr.live('mouseover', function() {
				if ($(this).hasClass(_obj.headCls)) {
					return;
				}
				$(this).toggleClass(_obj.hoverCls);

			});
			_tr.live('mouseout', function() {
				if ($(this).hasClass(_obj.headCls)) {
					return;
				}
				$(this).toggleClass(_obj.hoverCls);
			});		
		}
		
        _tr.live('click', function(e) {
			if(!_obj.checkIsRowSelect(e)){
				return;
			}
            if ($(this).hasClass(_obj.headCls)) {
                return;
            }
            if (_obj.scope) {
                _obj.scope.currentId = this.id;
            }
            _obj.currentId = this.id;

            $('.' + _obj.selectCls).removeClass(_obj.selectCls);
            $(this).toggleClass(_obj.selectCls);
			
			//用于扩展类的事件处理
			if(_obj.rowClick){
				_obj.rowClick.call(_obj,this.id,this);			
			}
			
			//点击事件
			if(_obj.onClick){
				_obj.onClick.call(_obj.scope,this.id,this);
			}

			//选中事件
            if (_obj.afterSelect) {
                _obj.afterSelect.call(_obj.scope, this.id, this);
            }
        });
       
		
		//展开收起按钮
		$('#collapse_'+this.renderTo).live('click',function(){
			if(this.className==_obj.collapsedCls){
				this.className=_obj.expandCls;
				if(_obj.animation){				
					_obj.mainDom.slideUp();
				}else{
					_obj.mainDom.hide();
				}
				this.title='展开';
				_obj.titleDom.css('border-bottom-width','1px');
			}else{
				this.className=_obj.collapsedCls;				
				if(_obj.animation){				
					_obj.mainDom.slideDown();
				}else{
					_obj.mainDom.show();
				}
				this.title='收起';		
				_obj.titleDom.css('border-bottom-width','0px');	
			}
		});
		
		//导出按钮
		$('#export_'+this.renderTo).live('click',function(){
			_obj.exportData();
		});
		
	},
	initComponent:function(){
		if(!this.renderTo){
			throw new Error('renderTo is need!');
		}
		this.el=$('#'+this.renderTo);
		this.init();		
		this.setSize();
		this.initEvent();
		if(this.autoLoad){
			this.load();
		}
		
		if(this.createTitleTool){
			this.initButton(this.createTitleTool(),this.titleDom);
			if(this.afterRenderTitleTool){
				this.afterRenderTitleTool.call(this);
			}
		}
	}
});

/**
*@description 数据列表
*/
Chenxin.UI.Grid = Chenxin.extend(Chenxin.UI.BaseGrid, {
    columns: {},
    headCls: 'x-grid-head', 		//头部样式
    bodyCls: 'x-grid-body', 		//身体样式
    emptyText: '没有记录',
    ml: 0,
    hasRowNumber: true,
    hasCheckBox: true,
    cellHeight: 23,
    colCount: 0,
    /**
    *@description 创建头部工具条
    */
    createTitleToolBar: Chenxin.emptyFn,
    afterHeadSelect: Chenxin.emptyFn,
    extensible: true, //'扩展功能，锁定列，列扩大等'
    gridType: 'table',
    cellBorder: false, 			//右边竖线
    sortDir: {						//排序
        field: '', 			//字段名
        dir: ''					//方向，asc或者desc
    },
    exportData: function() {
        var _h = '<table>';
        _h += this.headDom.find('table').html();
        _h += this.bodyDom.find('table').html();
        _h += '</table>';
        Chenxin.Fn.exportToExcel(_h, this.expertFileName);
    },
    createHead: function(head) {
        this.columns = head || this.columns;
        this.createHeadList(this.columns);
        if (this.columns && this.columns != {}) {
            this.headDom.empty();


            var _tr = document.createElement(this.rowTagName);
            var _this = this;

            //行号码
            if (this.hasRowNumber) {
                this.colCount += 1;
                $(_tr).append('<' + this.cellTagName + ' class="x-grid-row-num">&nbsp;&nbsp;&nbsp;&nbsp;</' + this.cellTagName + '>');
            }
            //选择框
            if (this.hasCheckBox) {
                this.colCount += 1;
                $(_tr).append('<' + this.cellTagName + ' class="x-grid-row-chk"><input type="checkbox" name="chk_all_row" id="chk_all_' + this.renderTo + '" /></' + this.cellTagName + '>');
            }

            //行头
            var _c = [];
            for (var c in this.columns) {
                var _h = this.columns[c];
                this.colCount += 1;

                if (_h.inField != false) {
                    _c.push(c);
                }
                var _td = this.createHeadCellDom(_h, c, true);
                $(_tr).append(_td);
            }

            //查询字段参数
            this.baseParam.field = _c.join(',');

            //渲染
            if (this.gridType == 'table') {
                var tb = document.createElement('table');
                tb.style.width = '100%';
                this.headDom.append($(tb).append(_tr));
            } else if (this.gridType == 'customize') {
                this.headDom.append(_tr);
            } else if (this.gridType == 'json') {
                this.headDom.append(_tr);
            }
            this.setHeadRowWidth();
        }
    },
    /**
    *@description 生成头部内容
    */
    createHeadCellDom: function(_h, c, autoSort, autoExtensible) {
        var _td = document.createElement(this.cellTagName);

        if (!_h.width) {
            _h.width = 160;
        }
        /**说明：不同步Head和数据行单元格的style设置
        if(_h.style){
        _s=_h.style.split(';');
        for(var i=0;i<_s.length;i++){
        $(_td).css(_s[i].split(':')[0],_s[i].split(':')[1]);
        }
        }
        */
        _td.style.width = _h.width + 'px';
        _td.style.height = this.cellHeight + 'px';
        _td.style.lineHeight = (this.cellHeight - 1) + 'px';
        if (_h.create == false) {
            _td.style.display = 'none';
        }
        _td.f = c;

        if (autoSort) {
            var sf = _h.sortField || '';
            sf = sf.toLowerCase();

            var _sf = this.sortField.split(' ')[0].toLowerCase();
            if (this.sortDir.field.toLowerCase() == sf || this.sortDir.field.toLowerCase() == c.toLowerCase() || _sf == c.toLowerCase() || _sf == sf) {
                if (_sf == c.toLowerCase() || _sf == sf) {
                    $(_td).append('<span class="x-grid-sort-' + this.sortField.split(',')[0].split(' ')[1] + '">' + (_h.head || '') + '</span>');
                } else {
                    $(_td).append('<span class="x-grid-sort-' + this.sortDir.dir + '">' + (_h.head || '') + '</span>');
                }
            } else {
                $(_td).append('<span>' + (_h.head || '') + '</span>');
            }

            $(_td).bind('click', { scope: this }, function(e) {
                if (e.target.tagName == 'DD' || e.target.tagName == 'SPAN') {
                    e.data.scope.headSelect(this, e.data.scope.field);
                }
            });
        } else {
            $(_td).append('<span>' + (_h.head || '') + '</span>');
        }

        if (autoExtensible == undefined) {
            autoExtensible = true;
        }
        if (this.extensible && !_h.items && autoExtensible) {
            var _ea = document.createElement('a');
            _ea.className = 'x-grid-headcell-extend';
            _ea.style.left = (_h.width - 15) + 'px';
            _ea.style.height = (this.cellHeight) + 'px';
            _ea.style.top = (-this.cellHeight) + 'px';
            $(_ea).bind('click', { h: _h, c: c, scope: this }, function(e) {
                e.data.scope.showHeadExtend.call(e.data.scope, e.data.h, e.data.c, $(this));
            });
            $(_td).append(_ea);


            $(_td).bind('mouseover', { scope: this, ea: _ea }, function(e) {
                if (e.target.tagName == 'DD' || e.target.tagName == 'SPAN') {
                    $(e.data.ea).addClass('x-grid-headcell-extend-hover');
                } else if (e.target.tagName == 'A') {
                    $(e.data.ea).removeClass('x-grid-headcell-extend-hover');
                }
            });


            $(_td).bind('mouseleave', { scope: this, ea: _ea }, function(e) {
                if (e.target.tagName == 'DD' || e.target.tagName == 'SPAN') {
                    $(e.data.ea).removeClass('x-grid-headcell-extend-hover');
                }
            });
        }

        return $(_td);
    },
    lockColumn: function(isLock, el) {
        if (this.columns[el.c].isLock == isLock || (this.columns[el.c].isLock == undefined && !isLock)) {
            return;
        }
        this.lockCell(isLock, el.c, this.columns);
    },
    lockCell: function(isLock, c, field, _index) {
        if (!this.headExtend) {
            this.createHeadList(this.columns);
        }
        this.createLockDom();

        var sourceHeadDom = isLock ? this.headDom : this.lockHeadDom;
        var targetHeadDom = isLock ? this.lockHeadDom : this.headDom;
        _index = _index != undefined ? _index : this.getCellIndex(c, field[c].isLock); //this.getCellIndex(c,sourceHeadDom);

        field[c].isLock = isLock; //标记已经锁定

        //获取宽度
        var sourceWidth = this.getColumnsWidth(!isLock);
        var targetWidth = this.getColumnsWidth(isLock);

        if (isLock && targetWidth > this.mainDom.width()) {//判断锁定列宽度不能超过表格宽度
            alert('锁定列宽度不能超过表格宽度!');
            field[c].isLock = false;
            return;
        }

        var _this = this;
        var lockWidth = isLock ? targetWidth : sourceWidth;

        targetHeadDom.find(this.rowTagName).width(targetWidth);
        sourceHeadDom.find(this.rowTagName).width(sourceWidth);

        //设置两个Dom的宽度
        this.lockDom.width(lockWidth);
        this.unLockDom.width(this.mainDom.width() - lockWidth - 1);

        this.lockRowCell(sourceHeadDom, targetHeadDom, sourceWidth, targetWidth, _index, isLock, c);
    },
    lockRowCell: function(sourceHeadDom, targetHeadDom, sourceWidth, targetWidth, _index, isLock, c) {
        //移动Head
        targetHeadDom.find(this.rowTagName).append(sourceHeadDom.find(this.rowTagName).children().eq(_index));

        var sourceBodyDom = isLock ? this.bodyDom : this.lockBodyDom;
        var targetBodyDom = isLock ? this.lockBodyDom : this.bodyDom;

        var sourceRowList = sourceBodyDom.find(this.rowTagName);
        var targetRowList = targetBodyDom.find(this.rowTagName);
        sourceRowList.each(function(i) {
            var _tr = targetRowList.eq(i);
            _tr.append($(this).children().eq(_index));
            _tr.width(targetWidth);
            $(this).width(sourceWidth);
        });
    },
    createLockDom: function() {
        if (!this.lockDom) {
            this.lockDom = this.createDom('x-grid-lockdom');
            this.lockHeadDom = this.createHeadDom();
            this.lockHeadDom.append('<dl></dl>');
            this.lockBodyDom = this.createBodyDom();
            if (this.height) {
                this.lockBodyDom.height(this.bodyDom[0].clientHeight);
                this.lockBodyDom.css('overflow', 'hidden');
            }

            this.lockDom.append(this.lockHeadDom);
            this.lockDom.append(this.lockBodyDom);

            this.unLockDom = this.createDom('x-grid-unlockdom');

            this.unLockDom.append(this.headDom);
            this.unLockDom.append(this.bodyDom);
            this.mainDom.append(this.lockDom);
            this.mainDom.append(this.unLockDom);
            this.mainDom.width(this.el.width() - 2);

            var _width = 0;
            if (this.hasRowNumber) {
                this.lockHeadDom.find(this.rowTagName).append(this.headDom.find(this.cellTagName).eq(0));
                _width += 21;
            }
            if (this.hasCheckBox) {
                this.lockHeadDom.find(this.rowTagName).append(this.headDom.find(this.cellTagName).eq(0));
                _width += 21;
            }
            this.lockHeadDom.find(this.rowTagName).width(_width);

            var rowList = this.bodyDom.find(this.rowTagName);
            for (var i = 0; i < rowList.length; i++) {
                var _row = $(document.createElement(this.rowTagName));
                _row.addClass('x-grid-lockrow');
                _row.width(_width);
                _row.height(rowList.eq(i).height());
                //_row.height(this.cellHeight);
                if (i % 2 == 1) {
                    _row.addClass('x-grid-row-odd');
                }
                if (this.hasRowNumber) {
                    _row.append(rowList.eq(i).find(this.cellTagName).eq(0));
                }
                if (this.hasCheckBox) {
                    _row.append(rowList.eq(i).find(this.cellTagName).eq(0));
                }
                this.lockBodyDom.append(_row);
            }
        }
    },
    showHeadExtend: function(_h, c, el) {
        if (!this.headExtend) {
            this.createHeadList(this.columns);
        }
        this.headExtend.show();
        this.liLock[0].c = c;
        this.liUnLock[0].c = c;

        this.headExtend.css('left', el.offset().left + 'px');
        this.headExtend.css('top', (el.offset().top + 25) + 'px');
        this.headExtend.show();
    },
    createHeadList: function(field) {
        this.headExtend = $(document.createElement('ul'));
        this.headExtend.addClass('x-grid-headextend');
        this.headExtend.hide();

        this.liLock = $(document.createElement('li'));
        this.liLock.attr('title', '锁定该列');
        this.liLock.append('<span class="x-lock-on"></span>');
        this.liLock.append('<span>锁定该列</span>');
        this.liLock.bind('click', { scope: this }, function(e) {
            e.data.scope.lockColumn.call(e.data.scope, true, this);
            //alert(e.data.scope.columnIndex[this.c]);
            e.data.scope.headExtend.find('li').eq(e.data.scope.columnIndex[this.c]).children().eq(2).show();
            e.data.scope.headExtend.hide();
        });
        this.headExtend.append(this.liLock);

        this.liUnLock = $(document.createElement('li'));
        this.liUnLock.attr('title', '解锁该列');
        this.liUnLock.append('<span class="x-lock-off"></span>');
        this.liUnLock.append('<span>解锁该列</span>');
        this.liUnLock.bind('click', { scope: this }, function(e) {
            e.data.scope.lockColumn.call(e.data.scope, false, this);
            e.data.scope.headExtend.find('li').eq(e.data.scope.columnIndex[this.c]).children().eq(2).hide();
            e.data.scope.headExtend.hide();
        });
        this.headExtend.append(this.liUnLock);

        this.headExtend.append('<hr style="width:134px"/>')


        var columnCount = 0;
        this.columnIndex = {};
        var ii = 2;
        //生成列
        for (var f in field) {
            this.columnIndex[f] = ii;
            ii++;

            var _li = document.createElement('li');
            $(_li).append('<span class="x-chk-off' + (field[f].create != false ? ' x-chk-on' : '') + '"></span>');
            $(_li).append('<span>' + field[f].head || f + '</span>');
            $(_li).append('<span style="display: none;" class="x-lock-on fr"></span>');
            _li.field = f;
            _li.title = field[f].head || f;
            if (field[f].inExpand == false) {
                _li.style.display = 'none';
            }
            var _this = this;
            this.headExtend.find('li').each(function() {
                if (this.field == f) {
                    $(this).find('span')[fn == 'hide' ? 'removeClass' : 'addClass']('x-chk-on');
                }
            })
            if (field[f].create != false) {
                columnCount++;
            }
            $(_li).bind('click', { scope: this }, function(e) {
                var h = field[this.field]
                if (h.isLock) {
                    alert('该列已锁定，不能隐藏！');
                    return;
                }

                var chk = $(this).find('span').eq(0);
                if (chk.hasClass('x-chk-on')) {
                    if (columnCount == 1) {
                        alert('至少保留一列显示！');
                        return;
                    }
                    columnCount -= 1;
                    chk.removeClass('x-chk-on');
                    e.data.scope.showColumn.call(e.data.scope, false, this.field, h, this);
                } else {
                    columnCount += 1;
                    chk.addClass('x-chk-on');
                    e.data.scope.showColumn.call(e.data.scope, true, this.field, h, this);
                }
            });

            this.headExtend.append(_li);
        }

        this.el.append(this.headExtend);
        this.headExtend.find('li').mouseover(function() {
            $(this).addClass('x-grid-headextend-hover');
        });
        this.headExtend.find('li').mouseleave(function() {
            $(this).removeClass('x-grid-headextend-hover');
        });

        var autoHide = null;

        var h = this.headExtend;
        this.headExtend.mouseleave(function() {
            autoHide = setTimeout(function() {
                h.hide();
            }, 400);
        });
        this.headExtend.mouseover(function() {
            if (autoHide) {
                clearTimeout(autoHide);
            }
        });

    },
    getCellIndex: function(c, isLock) {
        isLock = isLock == undefined ? false : isLock;
        var dom = isLock ? this.lockHeadDom : this.headDom;
        var index = -1;
        dom.find(this.rowTagName).children().each(function(i) {
            if (this.f == c) {
                index = i;
                return false;
            }
        });
        return index;
    },
    showColumn: function(isShow, c, h, el) {
        if (!this.headExtend) {
            this.createHeadList(this.columns);
        }
        var _this = this;
        var fn = isShow ? 'show' : 'hide';
        h.create = isShow;

        if (h.isLock) {//锁定列不能隐藏
            return;
        }

        var _index = this.getCellIndex(c, false); //锁定列不能隐藏，第二个参数为false
        //var _width=this.getColumnsWidth(false);//锁定列不能隐藏，第二个参数为false，获取的是非锁定列的宽度

        this.headDom.children().eq(0).children().eq(_index)[fn](); //隐藏head的cell
        //_dl.width(_width);//设置head的cell的容器宽度

        this.showRowColumn(_index, fn, c);
        if (this.lockDom) {//判断表格是否进行过锁定，有则重新设置Dom的宽度
            var _w = this.getColumnsWidth(true);
            this.lockDom.width(_w);
            this.unLockDom.width(this.mainDom.width() - _w - 1);
        }
    },
    showRowColumn: function(index, fn, c) {
        var _width = this.getColumnsWidth(false);
        var _width = _width < this.bodyDom.width() ? this.bodyDom.width() : _width;
        this.headDom.children().eq(0).width(_width);
        this.bodyDom.children().each(function() {
            $(this).children().eq(index)[fn]();
            $(this).width(_width);
        });
    },
    getSelectList: function() {
        return this.getSelectRecord().join(',');
    },
    getSelectLength: function() {
        if (!this.hasCheckBox) {
            return 0;
        }
        var _length = 0;
        $('#' + this.renderTo + ' :checked[name="chk_row"]').each(function(i) {
            _length++;
        });
        return _length;
    },
    getSelectRecord: function() {
        if (!this.hasCheckBox) {
            return '';
        }
        var idList = [];
        $('#' + this.renderTo + ' :checked[name="chk_row"]').each(function(i) {
            if (this.value != "null") {
                idList.push(this.value);
            }
        });
        return idList;
    },
    clear: function() {
        this.bodyDom.empty();
        if (this.extensible && this.lockDom) {
            this.lockDom.remove();
            delete this.lockDom;
            this.mainDom.append(this.headDom);
            this.mainDom.append(this.bodyDom);
            this.unLockDom.remove();
            delete this.unLockDom;
        }
    },
    render: function(data) {
        var _obj = this;
        if (data.gridWidth) {
            this.gridWidth = data.gridWidth;
        } else {
            this.gridWidth = 0;
        }

        // var _sameHead=true;
        if (data.head) {
            // if(Chenxin.Fn.equals(this.columns,{})){
            // _sameHead=false;
            // }else{
            // _sameHead=Chenxin.Fn.equals(this.oldHead,data.head);
            // }
            // if(!_sameHead){
            // this.oldHead={};
            // Chenxin.apply(this.oldHead,data.head);					
            // }
            this.createHead(data.head);
            // this.createHead(_sameHead?this.columns:data.head);
        } else {
            if (this.extensible) {
                this.createHead(this.columns);
            }
        }


        if (data.count) {
            if (this.gridType == 'table') {
                this.bodyDom.append('<table cellspacing="1" style="width:100%;">' + data.html + '</table>');
            } else if (this.gridType == 'customize') {
                this.bodyDom.append(data.html);
            }

            var headCell = this.headDom.find(this.cellTagName);
            this.bodyDom.find(this.rowTagName).each(function(i) {
                if (_obj.hasCheckBox) {
                    _obj.addRowChk(this);
                }
                if (_obj.hasRowNumber) {
                    _obj.addRowNum(this, i);
                }
                if ((_obj.gridType == 'table' && i == 0) || _obj.gridType != 'table') {
                    $(this).find(_obj.cellTagName).each(function(index) {
                        var _hc = headCell.eq(index)[0];
                        if (_hc && _hc.f) {
                            if (_obj.cellBorder) {
                                $(this).css('border-right-width', '1px');
                                $(this).width(_obj.columns[_hc.f].width);
                            } else {
                                $(this).width(_obj.columns[_hc.f].width + 1);
                            }
                            if (_obj.columns[_hc.f].style) {
                                var sl = _obj.columns[_hc.f].style.split(';');
                                for (var ii = 0; ii < sl.length; ii++) {
                                    if (sl[ii]) {
                                        var style = sl[ii].split(':');
                                        $(this).css(style[0], style[1]);
                                    }
                                }
                            }
                        }
                    });
                }
            });
            // if(this.extensible&&_sameHead){		
            if (this.extensible && data.count) {
                for (var f in this.columns) {
                    if (this.columns[f].isLock) {
                        var _index = this.getCellIndex(f, false);
                        if (!this.lockDom) {
                            if (this.hasRowNumber) {
                                _index--;
                            }
                            if (this.hasCheckBox) {
                                _index--;
                            }
                        }
                        this.lockCell(true, f, this.columns, _index);
                    }
                    if (this.columns[f].create == false) {
                        this.showColumn(false, f, this.columns[f]);
                    }
                }
            }

            if (!data.count && this.lockBodyDom) {
                this.lockBodyDom.find('dd').width(this.lockBodyDom.width() - 1);
            }

            this.setBodyRowWidth();
            this.resetRowCls(this.bodyDom);
        } else {
            if (this.gridType == 'table') {
                this.bodyDom.append('<table style="width:100%;"><tr class="x-grid-row"><td style="text-align:center;" colspan="' + this.colCount + '">' + this.emptyText + '</td></tr></table>');
            } else {
                this.bodyDom.append('<dl style="width:100%;"><dd class="x-grid-row" style="width:100%; text-align:center;"><dd style="text-align:center;" colspan="' + this.colCount + '">' + this.emptyText + '</dd></dl>');
            }
        }
        if (this.ml) {
            this.headDom.find(this.gridType == 'table' ? 'table' : 'dl').css('margin-left', -this.ml + 'px');
            this.bodyDom.scrollLeft(this.ml);
        }
        this.resetPageBar(data);

    },
    addRowNum: function(el, index) {
        $(el).prepend(this.createRowNum(this.cellTagName, index)); //'<'+this.cellTagName+' class="x-grid-row-num" style="border-right-width:1px;">' + index+ '</'+this.cellTagName+'>');
    },
    addRowChk: function(el) {
        $(el).prepend(this.createRowChk(this.cellTagName, el.id)); //'<'+this.cellTagName+' class="x-grid-row-chk" style="border-right-width:1px;"><input type="checkbox" id="chk_' + el.id + '" value="' + el.id + '" name="chk_row"/></'+this.cellTagName+'>');				
    },
    createRowChk: function(tagName, id) {
        return '<' + tagName + ' class="x-grid-row-chk" style="border-right-width:1px;"><input type="checkbox" id="chk_' + id + '" value="' + id + '" name="chk_row"/></' + tagName + '>';
    },
    createRowNum: function(tagName, index) {
        return '<' + tagName + ' class="x-grid-row-num" style="border-right-width:1px;">' + (index + 1) + '</' + tagName + '>';
    },
    headSelect: function(el, field) {
        if (!this.sortDir) {
            this.sortDir = {
                field: '',
                dir: ''
            };
        }
        field = field || this.columns;
        if (field[el.f].sortable) {
            $('.x-grid-sort-asc').removeClass('x-grid-sort-asc');
            $('.x-grid-sort-desc').removeClass('x-grid-sort-desc');

            var _s = field[el.f].sortField || el.f;

            if (this.sortDir.field == _s) {
                if (this.sortDir.dir == 'asc') {
                    this.sortDir.dir = 'desc';
                } else {
                    this.sortDir.dir = 'asc';
                }
            } else {
                this.sortDir.field = _s;
                this.sortDir.dir = 'desc';
            }
            var sf = this.sortDir.field.split(',');
            for (var i = 0; i < sf.length; i++) {
                sf[i] += ' ' + this.sortDir.dir;
            }
            this.sortField = sf.join(',');
            //this.sortField=this.sortDir.field+' '+this.sortDir.dir;
            el.children[0].className = 'x-grid-sort-' + this.sortDir.dir;
            /*			
            if (this.sortDir[el.f]) {
            if (this.sortDir[el.f] == 'asc') {
            this.sortDir[el.f] = 'desc';
            } else {
            this.sortDir[el.f] = 'asc';
            }
            } else {
            this.sortDir[el.f] = 'asc';
            }
            this.sortDir[el.f] = this.sortDir[el.f];
            this.sortField = el.f + ' ' + this.sortDir[el.f];
            el.children[0].className = 'x-grid-sort-' + this.sortDir[el.f];
            */


            this.sortRecord();
        }
        if (this.afterHeadSelect) {
            this.afterHeadSelect(el);
        }

    },
    sortRecord: function() {
        this.ml = this.bodyDom.scrollLeft();
        this.reload();
    },
    createBodyDom: function() {
        return this.createDom(this.bodyCls || 'x-grid-body');
    },
    createHeadDom: function() {
        return this.createDom(this.headCls || 'x-grid-head');
    },
    init: function() {
        Chenxin.UI.Grid.superclass.init.call(this);

        var _width = this.el.width();
        if (_width) {
            this.el.css('width', _width + 'px');
        } else {
            this.el.css('width', _width + '100%');
        }

        this.headDom = this.createHeadDom();
        this.mainDom.append(this.headDom);
        this.bodyDom = this.createBodyDom();
        this.mainDom.append(this.bodyDom);
        this.createHead();

    },
    initWidth: function() {
        if (this.columns) {
            var _width = this.el.width();
            var _w = 0;
            var i = 0;
            if (this.hasRowNumber) {
                i += 1;
                //_w+=this.headDom.find(this.rowTagName).find(this.cellTagName).eq(1).width();
                _w += 20;
            }
            if (this.hasCheckBox) {
                i += 1;
                //_w+=this.headDom.find(this.rowTagName).find(this.cellTagName).eq(0).width();
                _w += 20;
            }
            if (this.count) {
                for (var _c in this.columns) {
                    if (_c.create != false) {
                        _w += this.columns[_c].width;
                    }
                    if (this.gridType == 'table') {
                        var _tr = this.bodyDom.find('tr').eq(0);
                        _tr.find('td').eq(i).width(this.columns[_c].width);
                    } else if (this.gridType == 'customize') {
                        var _obj = this;
                        this.bodyDom.find('dl').each(function() {
                            //$(this).find('dd').eq(i).width(_obj.columns[_c].width+1);
                            var _dd = $(this).find('dd').eq(i);
                            if (_obj.cellBorder) {
                                _dd.css('border-right-width', '1px');
                                _dd.width(_obj.columns[_c].width);
                            } else {
                                _dd.width(_obj.columns[_c].width + 1);
                            }
                        });
                    }
                    i++;
                }
            }
            if (_width) {
                this.el.css('width', _width + 'px');
            } else {
                this.el.css('width', _width + '100%');
            }

            if ((_w > this.bodyDom[0].clientWidth) || (this.bodyDom[0].clientWidth - this.bodyDom[0].offsetWidth > 2)) {
                if (this.bodyDom[0].clientWidth) {
                    if (this.gridType == 'table') {
                        this.headDom.find('table').css('width', _w + 'px');
                        this.bodyDom.find("table").css('width', _w + 'px');
                    } else if (this.gridType == 'customize') {
                        this.headDom.find('dl').css('width', _w + 20 + 'px');
                        this.bodyDom.find("dl").css('width', _w + 20 + 'px');
                    } else if (this.gridType == 'json') {
                        this.headDom.find('dl').css('width', _w + 20 + 'px');
                        this.bodyDom.find("dl").css('width', _w + 20 + 'px');
                    }
                } else {

                }
            } else {
                if (this.gridType == 'table') {
                    this.mainDom.css('border-width', '1px 0px 0px 1px;');
                } else if (this.gridType == 'customize') {
                    //this.headDom.find('dl')[0].style.removeAttribute('width');					
                }
            }

            if (!this.height) {
                this.bodyDom.css('border-bottom-width', '0px');
            }
        }
        if (this.gridWidth) {
            this.headDom.find(this.rowTagName).css('width', this.gridWidth + 'px');
            this.bodyDom.find(this.rowTagName).css('width', this.gridWidth + 'px');
        }
    },
    getRecord: function(column) {
        if (this.currentId && column) {
            return $('#' + this.currentId).find(this.cellTagName).eq(this.getCellIndex(column)).text();
        }
        return '';
    },
    getGridWidth: function() {
        if (this.gridWidth) {
            return this.gridWidth;
        }
        return this.getColumnsWidth(false);
    },
    getColumnsWidth: function(isLock) {
        var _w = 0;
        if (isLock || (!isLock && !this.lockDom)) {
            if (this.hasRowNumber) {
                _w += 21;
            }
            if (this.hasCheckBox) {
                _w += 21;
            }
        }
        var field = this.columns;
        for (var c in field) {
            if (field[c].create != false) {
                if (isLock == undefined) {
                    _w += field[c].width + 1;
                } else {
                    if (field[c].isLock == undefined) {
                        field[c].isLock = false;
                    }
                    if (field[c].isLock == isLock) {
                        _w += field[c].width + 1;
                    }
                }
            }
        }
        if (this.gridType != 'table' && isLock == undefined) {
            return _w + 6;
        }
        return _w;
    },
    setHeadRowWidth: function() {
        this.setRowWidth(this.headDom);
    },
    setBodyRowWidth: function() {
        this.setRowWidth(this.bodyDom);
    },
    setRowWidth: function(dom) {
        this.gridWidth = this.getGridWidth();
        var _w = this.gridWidth;
        if ((_w >= dom[0].clientWidth) || (dom[0].clientWidth - dom[0].offsetWidth > 2)) {
            if (dom[0].clientWidth) {
                var rowTagName = 'dl';
                if (this.gridType == 'table') {
                    rowTagName = 'table';
                }
                dom.find(rowTagName).width(_w);
            } else {

            }
        } else {
            if (this.gridType == 'table') {
                this.mainDom.css('border-width', '1px 0px 0px 1px;');
            }
        }
    },
    rowClick: function(id, el) {
        if (this.hasCheckBox) {
            $('#' + this.renderTo + ' :checked[name="chk_row"]').attr('checked', false);
            $('#chk_' + id).attr('checked', true);
        }
    },
    initEvent: function() {
        var _obj = this;

        Chenxin.UI.Grid.superclass.initEvent.call(this);

        //点击
        $('#' + this.renderTo + ' :input[name="chk_row"]').live('click', function() {
            $('#' + this.value).toggleClass(_obj.selectCls);
            if (_obj.scope) {
                _obj.scope.currentId = this.id.substr(4);
            }
            _obj.currentId = this.v;
        });

        //全部选中按钮事件
        $('#chk_all_' + this.renderTo).live('click', function() {
            $('#' + _obj.renderTo + ' :input[name="chk_row"]').attr('checked', this.checked);

            if (this.checked) {
                _obj.bodyDom.find(_obj.rowTagName).addClass(_obj.selectCls);
            } else {
                _obj.bodyDom.find(_obj.rowTagName).removeClass(_obj.selectCls);
            }
        });

        //移动滚动条
        this.bodyDom.scroll(function() {
            if (_obj.gridType == 'table') {
                _obj.headDom.find('table').css('margin-left', -this.scrollLeft + 'px');
            } else {
                //_obj.headDom[0].scrollLeft=this.scrollLeft;
                _obj.headDom.find('dl').css('margin-left', -this.scrollLeft + 'px');
                if (_obj.lockBodyDom) {
                    _obj.lockBodyDom[0].scrollTop = this.scrollTop;
                }
            }
        });
    },
    resetRowCls: function(dom) {
        var _obj = this;
        dom.find(this.rowTagName).each(function(i) {
            if (i % 2 == 1) {//奇数行，添加样式，从0开始
                $(this).addClass('x-grid-row-odd');
            }
            $(this).addClass(_obj.rowCls);
        });
    },
    checkIsRowSelect: function(e) {
        if (e.target.tagName.toLowerCase() != this.cellTagName) {
            return false;
        }
        return true;
    },
    setSize: function() {
        if (this.width) {
            this.el.css('width', this.width + 'px');
        }
        if (this.height) {
            this.bodyDom.height(this.height);
        }
    },
    initComponent: function() {
        if (this.gridType == 'table') {
            this.rowTagName = 'tr';
            this.cellTagName = 'td';
        } else if (this.gridType == 'customize') {
            this.rowTagName = 'dl';
            this.cellTagName = 'dd';
        } else if (this.gridType == 'json') {
            this.rowTagName = 'dl';
            this.cellTagName = 'dd';
        }
        Chenxin.UI.Grid.superclass.initComponent.call(this);
        this.gridWidth = 0;
    }
});


Chenxin.UI.ExpandGrid=Chenxin.extend(Chenxin.UI.Grid,{	
	gridType:'customize',
	rowTagName:'dl',
	cellTagName:'dd',
	rowCls:'x-expand-grid-row',
	rowExpandCls:'x-grid-row-expand',//行点击展开样式
	rowExpandAble:false,			//是否有行点击展开
	rowExpandType:'single',			//单行点击展开，其他的收起，为multi为多行展开
	rowExpandHeight:180,
	exportData:function(){
		var _h='<table>';
		this.headDom.find('dl').each(function(){
			_h+='<tr>';
			$(this).find('dd').each(function(){
				_h+='<td>'+this.innerHTML+'</td>';
			});
			_h+='</tr>';
		});
		
		this.bodyDom.find('dl').each(function(){
			_h+='<tr>';
			$(this).find('dd').each(function(){
				if(this.style.display!='none'){
					_h+='<td>'+this.innerHTML+'</td>';				
				}
			});
			_h+='</tr>';
		});
		
		_h+='</table>';
		Chenxin.Fn.exportToExcel(_h,this.expertFileName);
	},
	/**
	*@description 行点击展开
	*/
	rowExpand:Chenxin.emptyFn,	
	/**
	*@description 行点击收起
	*/
	rowCollapse:Chenxin.emptyFn,
	rowClick:function(id,el){
		Chenxin.UI.ExpandGrid.superclass.rowClick.call(this,id,el);
		if(this.rowExpandAble){
			if(this.rowExpandType=='single'){
				$('.'+this.rowExpandCls).next().css('border-top-width','0px');
				$('.'+this.rowExpandCls).each(function(){
					$(this).remove();
					if(this.id.substr(4)!=id){
						$('#'+this.id.substr(4))[0].exp=undefined;					
					}
				});
			}
			if(!el.exp){
				$(el).next().css('border-top-width','1px');
				$(el).after('<dl class="'+this.rowExpandCls+'" id="exp_'+id+'"><dd class="row-expand-td" ></dd></dl>');
				el.exp=$('#exp_'+id).find('dd');
				el.exp.height(this.rowExpandHeight);
				if(this.rowExpand){
					this.rowExpand.call(this.scope,el.exp,el,this);
				}				
			}else{
				delete el.exp;
				if(this.rowCollapse){
					this.rowCollapse.call(this.scope,el.exp,el,this);
				}
			}
		}
	},
	
	initComponent:function(){
		Chenxin.UI.ExpandGrid.superclass.initComponent.call(this);
	}
});

Chenxin.UI.JsonGrid=Chenxin.extend(Chenxin.UI.Grid,{
	gridType:'json',
	rowCls:'x-expand-grid-row',
	rowExpandCls:'x-grid-row-expand',//行点击展开样式
	maxLevel:1,
	field:{},
	sortStyle:'remote',				//排序方式，local为本地对store的排序，remote为远程服务器刷新数据排序
	extensible:true,
	afterRender:Chenxin.emptyFn,
	cellHeight:23,
	rowRenderer:Chenxin.emptyFn,
	cellAlign:'center',			//单元格数据默认对齐方式，默认中间对齐
	autoOddCls:false,				//是否给奇数行添加样式
	exportType:'html',				//导出类型
	/**
	*@description 根据记录的ID获取记录
	*@recordId 要获取记录的ID
	*/
	getRecord:function(recordId){
		// if(!this.store.map&&this.modelId){
			// this.store.map={};
			// for(var i=0;i<this.store.rows.length;i++){
				// this.store.map[this.store.rows[i][this.modelId]]={};
				// this.store.map[this.store.rows[i][this.modelId]].index=i;
			// }
		// }
		if(!recordId){
			return null;
		}
		if(!this.store.map[recordId]){
			return null;
		}
		return this.store.rows[this.store.map[recordId].index];
	},
	/**
	*@description 根据记录的ID获取记录的字段
	*@recordId 要获取记录的ID
	*@field 要获取的字段
	*/
	getField:function(recordId,field){
		return this.getRecord(recordId)[field];
	},
	/**
	*@description 获取当前选中记录，没有选中则返回null
	*/
	getCurrentRecord:function(){
		if(this.currentId){
			return this.getRecord(this.currentId);
		}
		return null;
	},
	/**
	*@description 获取当前选中记录的字段，没有则返回null
	*@field 要获取的字段
	*/
	getCurrentField:function(field){
		if(this.currentId){
			return this.getCurrentRecord(this.currentId)[field];
		}
		return null;
	},
	getColumnsWidth:function(isLock){		
		var _w=0;
		if(isLock||(!isLock&&!this.lockDom)){
			if(this.hasRowNumber){
				_w+=21;
			}
			if(this.hasCheckBox){
				_w+=21;
			}		
		}
		var field=this.field;
		for(var c in field){
			if(field[c].create!=false){
				if(isLock==undefined){
					_w+=field[c].width+1;				
				}else{
					if(field[c].isLock==undefined){
						field[c].isLock=false;
					}
					if(field[c].isLock==isLock){						
						_w+=field[c].width+1;	
					}
				}
			}
		}
		if(this.gridType!='table'&&isLock==undefined){
			return _w+6;
		}
		return _w;	
	},
	getCellIndex:function(c,isLock){
		isLock=isLock==undefined?false:isLock;	
		var dom=isLock?this.lockHeadDom:this.headDom;
		var index=-1;
		var _this=this;
		dom.find(this.rowTagName).children().each(function(i){
			if(this.f==c){
				index=i;
				return false;
			}else{
				$(this).find(_this.cellTagName).each(function(ii){
					if(this.f==c){
						index=i;
						return false;
					}
				});
				if(index!=-1){
					return false;
				}
			}
		});
		return index;
	},
	lockColumn:function(isLock,el){
		if(this.field[el.c].isLock==isLock||(this.field[el.c].isLock==undefined&&!isLock)){
			return;
		}
		this.lockCell(isLock,el.c,this.field);
	},
	lockRowCell:function(sourceHeadDom,targetHeadDom,sourceWidth,targetWidth,_index,isLock,c){		
		var sourceBodyDom=isLock?this.bodyDom:this.lockBodyDom;
		var targetBodyDom=isLock?this.lockBodyDom:this.bodyDom;
		
		var sourceRowList=sourceBodyDom.find(this.rowTagName);
		var targetRowList=targetBodyDom.find(this.rowTagName);	

		var bc=this.setFieldAttr(c,'isLock',isLock,function(c,f){			
			this.headExtend.find('li').eq(this.columnIndex[f]).children().eq(2)[isLock?'show':'hide']();
		});
		
		//移动Head
		targetHeadDom.find(this.rowTagName).append(sourceHeadDom.find(this.rowTagName).children().eq(_index));
		
		sourceWidth=this.getColumnsWidth(!isLock);
		targetWidth=this.getColumnsWidth(isLock);
		
		
		var _this=this;
		var lockWidth=isLock?targetWidth:sourceWidth;
		
		targetHeadDom.find(this.rowTagName).width(targetWidth);		
		sourceHeadDom.find(this.rowTagName).width(sourceWidth);
		
		//设置两个Dom的宽度
		this.lockDom.width(lockWidth);
		this.unLockDom.width(this.mainDom.width()-lockWidth-1);
		
		
		
		sourceRowList.each(function(i){
			var _tr=targetRowList.eq(i);	
			for(var ii=0;ii<bc.length;ii++){
				_tr.append($(this).children().eq(bc[0]));			
			}
			_tr.width(targetWidth);
			$(this).width(sourceWidth);			
		});
	},
	showHeadExtend:function(_h,c,el){
		if(!this.headExtend){
			this.createHeadList(this.field);
		}	
		this.liLock[0].c=c;
		this.liUnLock[0].c=c;
		
		this.headExtend.css('left',el.offset().left+'px');			
		this.headExtend.css('top',(el.offset().top+25)+'px');
		this.headExtend.show();
	},
	showRowColumn:function(index,fn,c){
		var bc=this.setFieldAttr(c,'create',fn=='show'?true:false,function(c,f){
			this.headExtend.find('li').eq(this.columnIndex[f]).children().eq(0)[fn=='hide'?'removeClass':'addClass']('x-chk-on');
		});
		var _width=this.getColumnsWidth(false);		
		_width=_width<this.bodyDom.width()?this.bodyDom.width():_width;
		
		this.headDom.children().eq(0).width(_width);
		this.bodyDom.children().each(function(){
			for(var i=0;i<bc.length;i++){
				$(this).children().eq(bc[i])[fn]();				
			}
			$(this).width(_width);
		});
	},
	setFieldAttr:function(c,attr,value,callback){	
		var bc=[];
		var i=0;
		var dom=attr=='create'?this.headDom:(value==true?this.headDom:this.lockHeadDom);
		var _this=this;
		dom.find(this.rowTagName).children().each(function(){
			if(this.f==undefined||this.f!=''){//普通的单元格或者数字，Checkbox框，直接加1
				if(!_this.field[c].p&&this.f==c){//要查找的也是普通的单元格，找到后，直接跳出循环
					bc.push(i);
				}
				i++;
			}else if(this.f==''){//组合框
				$(this).children().each(function(){//获取子元素
					if(_this.field[this.f]){//在this.field中存在的才是底层的普通单元格，加1
						if(_this.field[c].p&&_this.field[c].p==_this.field[this.f].p){							
							_this.field[this.f][attr]=value;
							bc.push(i);
							if(callback){
								callback.call(_this,c,this.f);
							}
						}
						i++;
					}
				});
				if(bc.length){//已经找到了，跳出循环
					return false;
				}
			}
		});
		return bc;
	},
	sortRecord:function(){	
		if(!this.sortDir.field){
			return;
		}
		
		this.ml=this.bodyDom.scrollLeft();
		if(this.sortStyle=='local'){
			var _this=this;
			this.store.rows.sort(function(x,y){
				if(typeof(x[_this.sortDir.field])=='number'){									
					if(_this.sortDir.dir=='asc'){
						return parseFloat(x[_this.sortDir.field])-parseFloat(y[_this.sortDir.field]);					
					}
					return parseFloat(y[_this.sortDir.field])-parseFloat(x[_this.sortDir.field]);	
				}else{				
					if(_this.sortDir.dir=='asc'){
						return x[_this.sortDir.field].localeCompare(y[_this.sortDir.field]);				
					}
					return y[_this.sortDir.field].localeCompare(x[_this.sortDir.field]);
				}		
			});
			this.store.isSort=true;
			this.render(this.store);
		}else{
			Chenxin.UI.JsonGrid.superclass.sortRecord.call(this);
		}
	},
	exportData:function(){
		var _this = this;
		Chenxin.ajax({
            type: "get",
            dataType: "json",
            url: this.actionUrl,
            data: { op: 'checkpermit', code: 'export' },
            onSuccess: function(data) {
				Chenxin.Msg.Waiting.show();
				var _h='<table style="border:solid 1px #a6c9e2;border-collapse:collapse;" cellspacing="0" cellpadding="0">';		
				_h+=_this.createExportHead();
				_h+=_this.createExportBody();
				_h+='</table>';
				Chenxin.Msg.Waiting.hide();
				Chenxin.Fn.exportToExcel(_h,this.expertFileName);
            }
		});
		/*
		Chenxin.Msg.Waiting.show();
		var _h='<table style="border:solid 1px #a6c9e2;border-collapse:collapse;" cellspacing="0" cellpadding="0">';		
		_h+=this.createExportHead();
		_h+=this.createExportBody();
		_h+='</table>';
		Chenxin.Msg.Waiting.hide();
		Chenxin.Fn.exportToExcel(_h,this.expertFileName);*/
	},
	createExportHead:function(){
		var _h='';
		if(this.exportType=='data'){//数据形式导出				
			_h+='<tr style="height:22px;">';
			for(var f in this.field){
				if(this.field[f].create!=false&&this.field[f].canExport!=false){
					_h+='<td style="width:'+this.field[f].width+'px; border:solid 1px #a6c9e2;">'+(this.field[f].head||'')+'</td>';			
				}
			}
			_h+='</tr>';
		}else{//HTML形式导出
			var head={};
			function handlerColumns(column,level){
				level=level||1;
				var count=0;
				for(var c in column){
					head['level_'+level]=head['level_'+level]||[];
					head['level_'+level].push(column[c]);
					column[c].field=c;
					if(column[c].items){//递归
						column[c].children=handlerColumns(column[c].items,level+1);
					}
					count++;
				}
				return count;
			}
			handlerColumns(this.columns);
			for(var l in head){			
				_h+='<tr style="height:22px;">';
				for(var i=0;i<head[l].length;i++){
					if(head[l][i].create!=false){
						_h+='<td ';
						_h+=head[l][i].children?' colSpan="'+head[l][i].children+'"':'';
						if(this.maxLevel>1&&!head[l][i].children&&l=='level_1'){
							_h+=' rowSpan="'+this.maxLevel+'"';
						}
						_h+=' style="border:solid 1px #a6c9e2;text-align:center;';
						_h+=l==('level_'+this.maxLevel)?('width:'+(head[l][i].width||160)+'px;'):'';
						if(head[l][i].canExport!=false){
							_h+='">'+(head[l][i].head||'')+'</td>';						
						}else{
							_h+='"></td>';	
						}
					}
				}
				_h+='</tr>';
			}
		}
		return _h;
	},
	createExportBody:function(){
		var _h='';
		if (this.store==undefined) return '';
		
		for(var i=0;i<this.store.rows.length;i++){
			_h+='<tr style="height:22px;">';
			for(var f in this.field){
				if(this.field[f].create!=false&&this.field[f].canExport!=false){
					_h+='<td style="border:solid 1px #a6c9e2;width:'+this.field[f].width+'px;">'+((this.field[f].textModel==true)?'\'':'')+(this.field[f].renderer?this.field[f].renderer.call(this,this.store.rows[i][f]||'',f,this.store.rows):(this.store.rows[i][f]||''))+'</td>';
				}
			}
			_h+='</tr>';
		}
		return _h;
	},
	createHead:function(head){
		this.columns=head||this.columns;	
        if (this.columns && this.columns != {}) {
			this.headDom.empty();
			
            var _tr = document.createElement('dl');
			var _height=25;
            var _this = this;

			//行号码
            if (this.hasRowNumber) {
                this.colCount += 1;
                $(_tr).append('<dd class="x-grid-row-num">&nbsp;&nbsp;&nbsp;&nbsp;</dd>');
            }
			//选择框
            if (this.hasCheckBox) {
                this.colCount += 1;				
				$(_tr).append('<dd class="x-grid-row-chk"><input type="checkbox" name="chk_all_row" id="chk_all_'+this.renderTo+'" /></dd>');				
            }
            
			this.field={};
            for (var c in this.columns) {				
				$(_tr).append(this.createHeadCell(this.columns[c],c));
            }
			$(_tr).find('dd').each(function(i){
				if(this.parentNode.tagName=='DL'){
					this.style.height=_this.maxLevel*_this.cellHeight+(_this.maxLevel-1)+'px';
					this.style.lineHeight=_this.maxLevel*_this.cellHeight+(_this.maxLevel-1)+'px';
				}
			});
			
			this.headDom.append(_tr);	
			this.setHeadRowWidth();
        }	
		this.createHeadList(this.field);
	},
	createHeadCell:function(_h,c){
		_h.level=1;
		_h.width=_h.width||160;
		if(!_h.items){
			this.field[c]=_h;
			return this.createHeadCellDom(_h,c,true);
		}else{
			//超大父容器
			var _dom=$(document.createElement(this.cellTagName));
			_dom[0].f='';
			_dom.append(this.createHeadCellDom(_h,c,false));
			_dom.children().eq(0).css('border-bottom-width','1px');
			
			//生成
			this.levelContainer={};
			this.handlerColumnsItem(_h,c);
			var _cell;
			for(var level in this.levelContainer){
				for(var levelC in this.levelContainer[level]){
					var _hli=this.levelContainer[level][levelC];
					_hli.width=_hli.width||160;
					_cell=this.createHeadCellDom(_hli,levelC,_hli.isLeaf);
					if(!_hli.isLeaf){
						_cell.css('border-bottom-width','1px');					
					}
					_dom.append(_cell);
				}
				_cell.css('border-right-width','0px');
			}
			_dom.width(_h.width||160+1);
			
			_dom.find('dd:first').width(_h.width||160+1);
			return _dom;
		}
	},
	handlerColumnsItem:function(_h,p){
		this.levelContainer=this.levelContainer||{};
		_h.width=0;
		for(var ci in _h.items){			
			_h.items[ci].level=_h.level+1;
			this.levelContainer['level_'+(_h.level+1)]=this.levelContainer['level_'+(_h.level+1)]||{};
			this.levelContainer['level_'+(_h.level+1)][ci]=_h.items[ci];
			if(_h.items[ci].items){
				_h.items[ci].isLeaf=false;
				this.handlerColumnsItem(_h.items[ci],p);
			}else{
				_h.items[ci].isLeaf=true;
				this.field[ci]=_h.items[ci];
				this.field[ci].p=p;
			}
			this.maxLevel=this.maxLevel>(_h.level+1)?this.maxLevel:(_h.level+1);
			_h.width+=(_h.items[ci].width||160)+1;
		}
		_h.width-=1;
	},
	createStoreMap:function(){	
		if(this.store&&!this.store.map&&this.modelId){
			this.store.map={};
			for(var i=0;i<this.store.rows.length;i++){
				this.store.map[this.store.rows[i][this.modelId]]={};
				this.store.map[this.store.rows[i][this.modelId]].index=i;
			}
		}
	},
	deleteRecord:function(modelId){
		if(modelId&&this.store.map&&this.store.map[modelId]){
			this.store.rows.splice(this.store.map[modelId].index,1);
			delete this.store.map;
			this.createStoreMap();
			this.store.count-=1;
		}
	},
	reRender:function(){
		this.bodyDom.empty();
		delete this.store.map;
		this.render(this.store);
	},
	render:function(data){		
		var _obj = this;
		this.gridWidth=0;
		// var _sameHead=true;
		if (data.head) {
			// if(Chenxin.Fn.equals(this.columns,{})){
				// this.oldHead={};
				// Chenxin.apply(this.oldHead,data.head);
				// _sameHead=false;
			// }else{
				// _sameHead=Chenxin.Fn.equals(this.oldHead,data.head);
			// }
			//this.createHead(_sameHead?this.columns:data.head);
			this.createHead(data.head);
        }else{
			if(this.extensible){
				this.createHead(this.columns);
			}
		}
		
		this.bodyDom.empty();
		this.store=data;
		this.createStoreMap();
		if(!this.store.isSort&&this.sortDir.field&&this.sortStyle=='local'){
			this.sortRecord();
			return;
		}
		if (data.rows.length){
			if(data.rows){		
				this.bodyDom.empty();
				for(var i=0;i<data.rows.length;i++){
					this.bodyDom.append(this.createRow(data.rows[i],i));
				}
			}else{
				Chenxin.UI.JsonGrid.superclass.render.call(this,data);
			}
		}else{
			this.bodyDom.append('<dl class="x-expand-grid-row"><dd style="width: '+this.el.width()+'px; text-align: center; border-right-width: 1px;">'+this.emptyText+'</dd></dl>');		
		}
		
		if(this.afterRender){
			this.afterRender.call(this,data);
		}
				
				
		this.setBodyRowWidth();
		if(this.ml){
			this.headDom.find('dl').css('margin-left',-this.ml+'px');
			this.bodyDom.scrollLeft(this.ml);
		}
		if(this.extensible){		
			var p='';
			for(var f in this.field){
				if(this.field[f].isLock){
					this.field[f].isLock=false;
					if(!this.field[f].p){
						this.lockCell(true,f,this.field);
					}else{
						if(p!=this.field[f].p){
							p=this.field[f].p;
							this.lockCell(true,f,this.field);							
						}
					}
					this.field[f].isLock=true;
				}
				if(this.field[f].create==false&&this.columns[f]){//
					this.showColumn(false,f,this.field[f]);
				}
			}
		}
		if(!data.count&&this.lockBodyDom){
			this.lockBodyDom.find('dd').width(this.lockBodyDom.width()-1);			
		}
		
		this.resetPageBar(data);
	},
	createRow:function(row,index){
		var _dl=$(document.createElement('dl'));
		_dl.addClass(this.rowCls);
		_dl[0].id=row[this.modelId];
		if(this.autoOddCls&&index%2==1){
			_dl.addClass('x-grid-row-odd');
		}
		
		if(this.hasRowNumber){
			_dl.append(this.createRowNum(this.cellTagName,index));
		}
		if(this.hasCheckBox){
			_dl.append(this.createRowChk(this.cellTagName,row[this.modelId]));
		}
		//自定义行渲染
		if(this.rowRenderer){
			this.rowRenderer.call(this,row,index,_dl);
		}

		for (var c in this.field) {
			
			var _h = this.field[c];
			
			var _dd = document.createElement(this.cellTagName);
			
			var _i=(row[c]==null||row[c]=='null')?'':row[c];
			if(_h.renderer){
				_dd.innerHTML=_h.renderer(_i,c,row);
			}else{
				_dd.innerHTML=_i;			
			}
			_dd.title=_i;
			
			_dd.style.textAlign=this.cellAlign;
			
			
			if(_h.style){
				_s=_h.style.split(';');
				for(var i=0;i<_s.length;i++){
					$(_dd).css(_s[i].split(':')[0],_s[i].split(':')[1]);
				}
			}
			
			if(this.cellBorder){
				_dd.style.borderRightWidth='1px';
				_dd.style.width = _h.width + 'px';
			}else{			
				_dd.style.width = (_h.width+1) + 'px';
			}
			if (_h.create == false) {
				_dd.style.display = 'none';
			}
			_dl.append(_dd);
		}
		return _dl;		
	}, 
	initComponent:function(){
		this.field={};
		Chenxin.UI.JsonGrid.superclass.initComponent.call(this);
	}
});


Chenxin.UI.MultiRowGrid=Chenxin.extend(Chenxin.UI.JsonGrid,{
	cellHeight:16,
	cellBorder:true,
	getCellIndex:function(c,isLock){
		isLock=isLock==undefined?false:isLock;	
		var dom=isLock?this.lockHeadDom:this.headDom;
		var index=-1;
		var _this=this;
		dom.find(this.rowTagName).children().each(function(i){
			if(_this.field[c].p){//组合框
				if(this.f==_this.field[c].p){
					index=i;
					return false;
				}
			}else{//普通框
				if(this.f==c){
					index=i;
					return false;
				}
			}
		});
		return index;
	},	
	showRowColumn:function(index,fn,c){
		this.setFieldAttr(c,'create',fn=='show'?true:false,function(c,f){
			var _this=this;
			this.headExtend.find('li').eq(this.columnIndex[f]).children().eq(0)[fn=='hide'?'removeClass':'addClass']('x-chk-on');
		});
		var _width=this.getColumnsWidth(false);		
		_width=_width<this.bodyDom.width()?this.bodyDom.width():_width;
		
		this.headDom.children().eq(0).width(_width);
		this.bodyDom.children().each(function(){
			$(this).children().eq(index)[fn]();
			$(this).width(_width);
		});
	},
	lockRowCell:function(sourceHeadDom,targetHeadDom,sourceWidth,targetWidth,_index,isLock,c){		
		var sourceBodyDom=isLock?this.bodyDom:this.lockBodyDom;
		var targetBodyDom=isLock?this.lockBodyDom:this.bodyDom;
		
		var sourceRowList=sourceBodyDom.find(this.rowTagName);
		var targetRowList=targetBodyDom.find(this.rowTagName);	

		this.setFieldAttr(c,'isLock',isLock,function(c,f){			
			this.headExtend.find('li').eq(this.columnIndex[f]).children().eq(2)[isLock?'show':'hide']();
		});
		
		//移动Head
		targetHeadDom.find(this.rowTagName).append(sourceHeadDom.find(this.rowTagName).children().eq(_index));
		
		sourceWidth=this.getColumnsWidth(!isLock);
		targetWidth=this.getColumnsWidth(isLock);
		
		
		var _this=this;
		var lockWidth=isLock?targetWidth:sourceWidth;
		
		targetHeadDom.find(this.rowTagName).width(targetWidth);		
		sourceHeadDom.find(this.rowTagName).width(sourceWidth);
		
		//设置两个Dom的宽度
		this.lockDom.width(lockWidth);
		this.unLockDom.width(this.mainDom.width()-lockWidth-1);
		
		
		
		sourceRowList.each(function(i){
			var _tr=targetRowList.eq(i);	
				
			_tr.append($(this).children().eq(_index));
			_tr.width(targetWidth);
			
			$(this).width(sourceWidth);			
		});
	},
	setFieldAttr:function(c,attr,value,callback){	
		if(this.field[c].p){//组合框			
			for(var f in this.field){
				if(this.field[f].p==this.field[c].p){
					this.field[f][attr]=value;
					if(callback){
						callback.call(this,c,f);
					}
				}
			}
		}
	},
	getColumnsWidth:function(isLock){	
		var _w=0;
		if(isLock||(isLock==false&&!this.lockDom)){
			if(this.hasRowNumber){
				_w+=21;
			}
			if(this.hasCheckBox){
				_w+=21;
			}		
		}
		var field=this.field;
		var p='';
		for(var c in field){
			if(field[c].create!=false){				
				if(isLock==undefined){//锁定状态的
					if(!field[c].p){
						_w+=field[c].width+1;
					}else{
						if(p!=field[c].p){
							p=field[c].p;
							_w+=this.columns[field[c].p].width+1;
						}
					}				
				}else{	
					if(field[c].isLock==undefined){
						field[c].isLock=false;
					}
					if(field[c].isLock==isLock){					
						if(!field[c].p){
							_w+=field[c].width+1;
						}else{
							if(p!=field[c].p){
								p=field[c].p;
								_w+=this.columns[field[c].p].width+1;
							}
						}
					}
				}
			}
		}
		
		/* 
		
		var field=this.columns;
		for(var c in field){
			if(field[c].create!=false){
				if(isLock==undefined){
					if(field[c].items){						
						for(var cc in field[c].items){							
							if(field[c].items[cc].create!=false){
								_w+=field[c].width+1;
							}
							break;
						}
					}else{
						_w+=field[c].width+1;					
					}				
				}else{
					if(field[c].isLock==undefined){
						field[c].isLock=false;
					}
					if(field[c].items){
						for(var cc in field[c].items){
							if(field[c].items[cc].isLock==isLock&&field[c].items[cc].create!=false){
								_w+=field[c].width+1;
							}
							break;
						}
					}else{
						if(field[c].isLock==isLock){						
							_w+=field[c].width+1;	
						}
					}
					
				}
			}
		} */
		if(this.gridType!='table'&&isLock==undefined){
			return _w+6;
		}
		return _w;	
	},
	createExportHead:function(){
		if(this.exportType=='data'){
			return Chenxin.UI.MultiRowGrid.superclass.createExportHead.call(this);
		}else{
			var head={level_1:[]};
			var _h='';
			for(var c in this.columns){
				if(this.columns[c].items){
					var level=1;
					for(var ic in this.columns[c].items){
						head['level_'+level]=head['level_'+level]||[];
						this.columns[c].items[ic].field=ic;
						head['level_'+level].push(this.columns[c].items[ic]);
						level++;
					}
				}else{
					this.columns[c].field=c;
					this.columns[c].isTop=true;
					head.level_1.push(this.columns[c]);
				}
			}
			for(var l in head){
				_h+='<tr style="height:22px">';
				for(var i=0;i<head[l].length;i++){
					if(head[l][i].create!=false){					
						_h+='<td style="border:solid 1px #a6c9e2;text-align:center;width:'+(head[l][i].width||160)+'px;"';
						if(head[l][i].isTop){
							_h+=' rowSpan="'+this.maxLevel+'"';
						}
						if(head[l][i].canExport!=false){
							_h+='>'+head[l][i].head+'</td>';
						}else{
							_h+='></td>';						
						}
					}
				}
				_h+='</tr>';
			}
			this.exportHead=head;
			return _h;
		}
	},
	createExportBody:function(){
		if(this.exportType=='data'){
			return Chenxin.UI.MultiRowGrid.superclass.createExportBody.call(this);
		}else{
			if(this.exportHead){
				var r='';
				function createRow(level,row,head){
					var _r='<tr style="height:22px;">';
					
					for(var i=0;i<head[level].length;i++){					
						if(head[level][i].create!=false){					
							_r+='<td style="border:solid 1px #a6c9e2;text-align:center;width:'+(head[level][i].width||160)+'px;"';
							if(head[level][i].isTop){
								_r+=' rowSpan="'+this.maxLevel+'"';
							}
							if(head[level][i].canExport!=false){
								_r+='>'+((head[level][i].textModel==true)?'\'':'')+(head[level][i].renderer?(head[level][i].renderer.call(this,row[head[level][i].field]||'',head[level][i].field,row)):(row[head[level][i].field]||''))+'</td>';
							}else{
								_r+='></td>';						
							}
						}
					}
					_r+='</tr>';
					return _r;
				}
				for(var i=0;i<this.store.rows.length;i++){
					for(var l in this.exportHead){
						r+=createRow.call(this,l,this.store.rows[i],this.exportHead);
					}
				}
				return r;
			}
		}
	},
	createHeadCell:function(_h,c,dom,level){
		if(!_h.items){
			this.field[c]=_h;
			return this.createHeadCellDom(_h,c,true);
		}else{
			var x=this.createHeadCellDom(_h,c,false,false);
			x.find('span').remove();
			var _level=0;
			for(var _hi in _h.items){
				this.field[_hi]=_h.items[_hi];
				this.field[_hi].p=c;
				var cell=this.createHeadCellDom(_h.items[_hi],_hi,true);
				cell.height(this.cellHeight);
				cell.css('line-height',this.cellHeight+'px');
				x.append(cell);
				if(_level){
					cell.css('border-top-width','1px');
				}
				_level++;
			}
			if(_level>this.maxLevel){
				this.maxLevel=_level;
			}
			return x;	
		}
	},
	createRowChk:function(tagName,id){
		id=id||Math.random()*10000000000;
		var _d=$(document.createElement(this.cellTagName));
		_d.css('border-right-width','1px');
		_d.addClass('x-grid-row-chk');
		var _i=document.createElement('input');
		_i.id='chk_'+id;
		_i.value=id;
		_i.name='chk_row';
		_i.type="checkbox";
		_d.append(_i);
		
		return _d;
		//return '<'+tagName+' class="x-grid-row-chk" style="border-right-width:1px;"><input type="checkbox" id="chk_' + id + '" value="' + id + '" name="chk_row"/></'+tagName+'>';
	},
	createRowNum:function(tagName,index) {
		var _d=$(document.createElement(this.cellTagName));
		
		_d.css('border-right-width','1px');
		_d.addClass('x-grid-row-num');
		_d.text(index+1);
		return _d;
		//return '<'+tagName+' class="x-grid-row-num" style="border-right-width:1px;">' + (index+1)+ '</'+tagName+'>';
    },
	createRow:function(row,index){
		var _dl=$(document.createElement('dl'));
		_dl.addClass(this.rowCls);
		_dl[0].id=row[this.modelId];
		
		if(index%2==1){
			_dl.addClass('x-grid-row-odd');
		}
		var height=this.maxLevel*this.cellHeight;
		
		_dl.height(height+this.maxLevel-1);
		
		if(this.hasRowNumber){
			var rowCell=this.createRowNum(this.cellTagName,index);
			rowCell.css('height',height+'px');
			rowCell.css('line-height',height+'px');			
			
			_dl.append(rowCell);
		}
		if(this.hasCheckBox){
			var chkCell=this.createRowChk(this.cellTagName,row[this.modelId]);
			
			chkCell.css('height',height+'px');
			chkCell.css('line-height',height+'px');			
			_dl.append(chkCell);
		}
		
		for (var c in this.columns) {
			var _h = this.columns[c];			
			var _dd;
			if(_h.items){
				_dd=$(document.createElement(this.cellTagName));
				var _count=0;
				for(var _hh in _h.items){
					var _hd=this.createRowCell(_h.items[_hh],_hh,row);
					if(_count){
						_hd.css('border-top-width','1px');
					}
					_count++;
					_dd.append(_hd);
				}
			}else{
				_dd=this.createRowCell(_h,c,row);
			}
			
			
			_dd[0].style.textAlign=this.cellAlign;
			
			
			if(_h.style){
				_s=_h.style.split(';');
				for(var i=0;i<_s.length;i++){
					_dd.css(_s[i].split(':')[0],_s[i].split(':')[1]);
				}
			}
			
			if(this.cellBorder){
				_dd.css('border-right-width','1px');
				_dd.width(_h.width);
			}else{		
				_dd.width(_h.width+1);	
			}
			_dd.height(height+this.maxLevel-1);
			_dd.css('line-height',(height+this.maxLevel-1)+'px');
			_dl.append(_dd);
		}
		return _dl;
	},
	createRowCell:function(_h,c,row){
		var _td=document.createElement(this.cellTagName);
		var _i=(row[c]==null||row[c]=='null')?'':row[c];
		if(_h.renderer){
			_td.innerHTML=_h.renderer(_i,_h,row);
		}else{
			_td.innerHTML=_i;			
		}
		_td.title=_i;
		
		_td.style.textAlign='center';
		
		_td.style.width=_h.width+'px';
		_td.style.height=this.cellHeight+'px';
		_td.style.lineHeight=this.cellHeight+'px';
		if(_h.style){
			_s=_h.style.split(';');
			for(var i=0;i<_s.length;i++){
				$(_td).css(_s[i].split(':')[0],_s[i].split(':')[1]);
			}
		}
		if (_h.create == false) {
			_td.style.display = 'none';
		}
		
		return $(_td);
	},
	initComponent:function(){
		Chenxin.UI.MultiRowGrid.superclass.initComponent.call(this);
	}
});

Chenxin.UI.GroupReportGrid = Chenxin.extend(Chenxin.UI.JsonGrid, {
    hasTotal: true,                 //是否有统计行
    totalRow: {},
    rowGroupSetting: [],
    createLockDom: function() {
        if (!this.lockDom) {
            this.lockDom = this.createDom('x-grid-lockdom');
            this.lockHeadDom = this.createHeadDom();
            this.lockHeadDom.append('<dl></dl>');
            this.lockBodyDom = this.createBodyDom();
            if (this.height) {
                this.lockBodyDom.height(this.bodyDom[0].clientHeight);
                this.lockBodyDom.css('overflow', 'hidden');
            }

            this.lockDom.append(this.lockHeadDom);
            this.lockDom.append(this.lockBodyDom);

            this.unLockDom = this.createDom('x-grid-unlockdom');

            this.unLockDom.append(this.headDom);
            this.unLockDom.append(this.bodyDom);
            this.mainDom.append(this.lockDom);
            this.mainDom.append(this.unLockDom);
            this.mainDom.width(this.el.width() - 2);

            var _width = 0;
            if (this.hasRowNumber) {
                this.lockHeadDom.find(this.rowTagName).append(this.headDom.find(this.cellTagName).eq(0));
                _width += 21;
            }
            if (this.hasCheckBox) {
                this.lockHeadDom.find(this.rowTagName).append(this.headDom.find(this.cellTagName).eq(0));
                _width += 21;
            }
            this.lockHeadDom.find(this.rowTagName).width(_width);

        }
    },
    render: function(data, notGroupStore) {
        // $(document.body).append('<span>'+(new Date())+'</span>');
        if (this.lockDom) {
            this.lockDom.remove();
            delete this.lockDom;
        }
        this.gridWidth = 0;
        if (data.head) {
            this.createHead(data.head);
        }
        this.store = data;
        if (!notGroupStore) {
            this.groupStore();
        }
        this.createStoreMap();
        if (!this.store.isSort && this.sortDir.field && this.sortStyle == 'local') {
            this.sortRecord();
            return;
        }

        var r = {};
        this.createLockDom();
        for (var i = this.rowGroupSetting.length - 1; i >= 0; i--) {
            r[this.rowGroupSetting[i].field] = {
                data: [],
                dataMap: {},
                index: i,
                autoCount: i == (this.rowGroupSetting.length - 1) ? false : this.rowGroupSetting[i].autoCount,
                rowDom: this.createGroupRow(i)
            };
            this.createGroupHead(i);
        }
        if (this.hasTotal) {
            this.totalRow = {};
        }
        if (data.rows.length) {
            if (data.rows) {
                this.bodyDom.empty();

                for (var i = 0; i < data.rows.length; i++) {
                    for (var k = this.rowGroupSetting.length - 1; k >= 0; k--) {
                        var rr = this.rowGroupSetting[k].field;

                        if (!r[rr].data.length || (r[rr].data.length && (r[rr].data[r[rr].data.length - 1] != data.rows[i][rr]))) {//新的分组数据
                            if (r[rr].data.length) {//渲染前一个分组cell的高度

                                this.setCellSize(r, rr);
                            }

                            r[rr].data.push(data.rows[i][rr]);
                            r[rr].dataMap['x_' + rr + '_' + (r[rr].data.length - 1)] = {
                                content: data.rows[i][rr],
                                cellDom: this.createGroupCell(r[rr].index, data.rows[i][rr], r[rr].data.length - 1),
                                count: r[rr].autoCount ? 2 : 1
                            };
                            if (r[rr].autoCount) {
                                r[rr].dataMap['x_' + rr + '_' + (r[rr].data.length - 1)].countRow = {};
                            }
                            r[rr].rowDom.append(r[rr].dataMap['x_' + rr + '_' + (r[rr].data.length - 1)].cellDom);
                        } else {
                            r[rr].dataMap['x_' + rr + '_' + (r[rr].data.length - 1)].count++;
                        }
                    }

                    this.bodyDom.append(this.createRow(data.rows[i], i, r));
                }

                for (var rr in r) {
                    this.setCellSize(r, rr, true);
                }
            } else {
                Chenxin.UI.JsonGrid.superclass.render.call(this, data);
            }
        } else {
            this.bodyDom.append('<dl class="x-expand-grid-row"><dd style="width: ' + this.el.width() + 'px; text-align: center; border-right-width: 1px;">' + this.emptyText + '</dd></dl>');
        }
        if (this.afterRender) {
            this.afterRender.call(this, data);
        }
        this.setBodyRowWidth();
        if (this.ml) {
            this.headDom.find('dl').css('margin-left', -this.ml + 'px');
            this.bodyDom.scrollLeft(this.ml);
        }

        this.renderGroup();
        this.resetPageBar(data);


        // $(document.body).append('<span>'+(new Date())+'</span>');
    },
    createRow: function(row, index, r) {
        var _dl = $(document.createElement('dl'));
        _dl.addClass(this.rowCls);
        _dl[0].id = row[this.modelId];
        if (this.autoOddCls && index % 2 == 1) {
            _dl.addClass('x-grid-row-odd');
        }

        //自定义行渲染
        if (this.rowRenderer) {
            this.rowRenderer.call(this, row, index, _dl);
        }

        for (var c in this.field) {

            var _h = this.field[c];

            var _dd = document.createElement(this.cellTagName);

            var _i = (row[c] == null || row[c] == 'null') ? '' : row[c];

            if (typeof (_i) == 'number' && !r) {
                _i = _i.toFixed(2);
            }

            if (_h.renderer) {
                _dd.innerHTML = _h.renderer(_i, c, row);
            } else {
                _dd.innerHTML = _i;
            }
            _dd.title = _i;

            _dd.style.textAlign = this.cellAlign;


            if (_h.style) {
                _s = _h.style.split(';');
                for (var i = 0; i < _s.length; i++) {
                    $(_dd).css(_s[i].split(':')[0], _s[i].split(':')[1]);
                }
            }

            if (this.cellBorder) {
                _dd.style.borderRightWidth = '1px';
                _dd.style.width = _h.width + 'px';
            } else {
                _dd.style.width = (_h.width + 1) + 'px';
            }
            if (_h.create == false) {
                _dd.style.display = 'none';
            }
            _dl.append(_dd);

            if (r) {
                for (var rr in r) {
                    var countRow = r[rr].dataMap['x_' + rr + '_' + (r[rr].data.length - 1)].countRow;
                    if (countRow) {
                        if (countRow[c] == undefined) {
                            countRow[c] = row[c];
                        } else {
                            countRow[c] += row[c];
                        }
                    }
                }
            }

            if (this.totalRow && index != undefined && this.hasTotal) {
                if (this.field[c].inTotalRow == false) {
                    this.totalRow[c] = '';
                } else {
                    if (this.totalRow[c] == undefined) {
                        this.totalRow[c] = row[c];
                    } else {
                        this.totalRow[c] += row[c];
                    }
                }

            }
        }
        return _dl;
    },
    setCellSize: function(r, rr, isLast) {
        var tempDataMap = r[rr].dataMap['x_' + rr + '_' + (r[rr].data.length - 1)];
        tempDataMap.cellDom.height(this.cellHeight * tempDataMap.count + tempDataMap.count - 1);
        tempDataMap.cellDom.css('line-height', (this.cellHeight * tempDataMap.count + tempDataMap.count - 1) + 'px');

        if (r[rr].index != this.rowGroupSetting.length - 1) {
            tempDataMap.cellDom.css('border-right-width', '1px');
        }

        if (r[rr].autoCount) {//有统计，渲染统计行								
            //到子分组中去，渲染，统计行
            for (var j = r[rr].index + 1; j < this.rowGroupSetting.length; j++) {
                var countCell = this.createGroupCell(r[rr].index, (j == r[rr].index + 1 ? '小计' : ''), 'count_' + j).css('background-color', '#EAF4FE').css('line-height', this.cellHeight + 'px').height(this.cellHeight);
                if (j != this.rowGroupSetting.length - 1) {
                    countCell.css('border-right-width', '1px');
                }
                var children = r[this.rowGroupSetting[j].field].rowDom.children();
                children.eq(children.length - (isLast ? 1 : 2)).after(countCell);
            }

            this.bodyDom.append(this.createRow(r[rr].dataMap['x_' + rr + '_' + (r[rr].data.length - 1)].countRow).css('background-color', '#EAF4FE'));

        }

    },
    /**
    *@description 渲染分组Head
    */
    createGroupHead: function(i) {
        var _t = this.createHeadCellDom(this.rowGroupSetting[i], this.rowGroupSetting[i].field, false, false);
        _t.height(this.maxLevel * this.cellHeight + this.maxLevel - 1);
        _t.css('line-height', this.maxLevel * this.cellHeight + 'px');
        _t.css('border-bottom-width', '1px');
        if (i == this.rowGroupSetting.length - 1) {
            _t.css('border-right-width', '0px');
            this.rowGroupSetting[i].autoCount = false;
        }
        this.lockHeadDom.prepend(_t);
    },
    createGroupRow: function(i) {
        var _dl = $(document.createElement('dl'));
        _dl.width(this.rowGroupSetting[i].width + 1);
        _dl.css('float', 'left');
        _dl[0].id = 'x_gr_' + this.id + '_' + this.rowGroupSetting[i].field;
        this.lockBodyDom.prepend(_dl);
        return _dl;
    },
    createGroupCell: function(i, content, length) {
        d = $(document.createElement('dt'));
        d.attr('id', 'rg_' + this.id + '_' + this.rowGroupSetting[i].field + '_' + length);
        d.html(content);
        d.css('text-align', 'center');
        d.css('border', '0px solid #C5DBEC');
        d.css('border-bottom-width', '1px');
        d.css('border-bottom-width', '1px');
        return d;
    },
    createExportHead: function() {
        var _h = Chenxin.UI.GroupReportGrid.superclass.createExportHead.call(this);
        var _ha = '';
        for (var i = 0; i < this.rowGroupSetting.length; i++) {
            _ha += '<td style="border:solid 1px #a6c9e2;text-align:center;width:' + (this.rowGroupSetting[i].width || 160) + 'px;"';
            if (this.maxLevel > 1 && this.exportType == 'html') {
                _ha += ' rowSpan="' + this.maxLevel + '"';
            }

            _ha += '>' + this.rowGroupSetting[i].head + '</td>';
        }

        _h = '<tr style="height:22px;">' + _ha + _h.substr(25, _h.length);
        return _h;
    },
    createExportBody: function() {
        var r = '';

        var rs = [];
        var _this = this;
		if (this.lockBodyDom != undefined){
			this.lockBodyDom.children().each(function(i) {
				rs.push([]);
				var index = 0;

				$(this).children().each(function(j) {
					var _height = $(this).height();
					var _rowSpan = parseInt(_height / _this.cellHeight);
					_rowSpan = _rowSpan - parseInt(_rowSpan / _this.cellHeight);

					if (_this.exportType == 'data') {
						for (var _ii = 0; _ii < _rowSpan; _ii++) {
							rs[i].push({
								html: (((_ii + 1) == _rowSpan && _rowSpan != 1) ? '' : this.innerHTML),
								rowSpan: 1,
								width: $(this).width(),
								index: index
							});
							index += 1;
						}
					} else {
						rs[i].push({
							html: this.innerHTML,
							rowSpan: _rowSpan,
							width: $(this).width(),
							index: index
						});
						index += _rowSpan;
					}
				});
			});
		};
        this.bodyDom.children().each(function(i) {
            r += '<tr style="height:22px;' + (this.style.backgroundColor ? ('background-color:' + this.style.backgroundColor + ';') : '') + '">';
            for (var _in = 0; _in < rs.length; _in++) {
                for (var index = 0; index < rs[_in].length; index++) {
                    if (rs[_in][index].index == i) {
                        r += '<td  style="border:solid 1px #a6c9e2;text-align:center;width:' + rs[_in][index].width + ';"';
                        r += rs[_in][index].rowSpan > 1 ? (' rowSpan="' + rs[_in][index].rowSpan + '"') : '';
                        r += '>' + rs[_in][index].html + '</td>';
                    }
                }
            }
            r += this.innerHTML.replace(/\<DD /g, '<td ').replace(/\<dd /g, '<td ').replace(/\<\/DD\>/g, '</td>').replace(/\<\/dd\>/g, '</td>').replace(/border-right-width: 1px/g, 'border:solid 1px #a6c9e2');
            r += '</tr>'
        });
        return r;
    },
    renderGroup: function() {
        this.lockBodyDom.width(this.lockBodyDom.width());
        this.unLockDom.width(this.mainDom.width() - this.lockDom.width() - 1);
        this.lockBodyDom.height(this.bodyDom[0].clientHeight);
        if (this.height) {
            this.lockDom.css('border-bottom', '1px solid #C5DBEC');
        }
        this.renderTotal(); //渲染总计行
    },
    renderTotal: function() {
        if (this.hasTotal && this.store.rows.length && this.totalRow) {

            for (var r in this.totalRow) {
                if (typeof (this.totalRow[r]) == 'number') {
                    this.totalRow[r] = this.totalRow[r].toFixed(2);
                }
            }

            var _row = this.createRow(this.totalRow);
            _row.css('background-color', '#EAF4FE');
            var _pr = this.bodyDom.find('dl:last');
            _row.width(_pr.width());
            _pr.after(_row);
            var _this = this;
            if (!this.height) {
                this.lockBodyDom.height(this.lockBodyDom.height() + this.cellHeight + 1);
            }
            this.lockBodyDom.find('dl').each(function(i) {
                $(this).append('<dt style="background-color:#EAF4FE ;width:' + (!i ? (_this.rowGroupSetting[i].width || 160) : (_this.rowGroupSetting[i].width || 160) + 1) + 'px;border:1px solid #C5DBEC;border-width:0px ' + (i ? 0 : 1) + 'px 1px 0px;text-align:center;height:' + _this.cellHeight + 'px;line-height:' + _this.cellHeight + 'px">' + (i ? '' : '总计') + '</dt>');
            });
        }
    },
    groupStore: function() {
        var pfield = '';
        var _this = this;
        var _rsRecord = {};

        for (var i = 0; i < this.rowGroupSetting.length; i++) {
            this.store.rows.sort(function(x, y) {
                var _pp = pfield.split(',');
                for (var j = 0; j < _pp.length; j++) {//之前的排序字段相同，就不排序
                    if (y[_pp[j]] != x[_pp[j]]) {
                        return false;
                    }
                }

                return y[_this.rowGroupSetting[i].field].localeCompare(x[_this.rowGroupSetting[i].field]);
            });

            pfield += (pfield ? ',' : '') + this.rowGroupSetting[i].field;
        }
    },
    sortRecord: function() {
        if (!this.sortDir.field) {
            return;
        }

        this.ml = this.bodyDom.scrollLeft();
        if (this.sortStyle == 'local') {
            var _this = this;

            var _pp = [];
            for (var i = 0; i < this.rowGroupSetting.length; i++) {
                _pp.push(this.rowGroupSetting[i].field);
            }
            this.store.rows.sort(function(x, y) {
                for (var j = 0; j < _pp.length - 1; j++) {//之前的排序字段相同，就不排序
                    if (y[_pp[j]] != x[_pp[j]]) {
                        return false;
                    }
                }
                if (typeof (x[_this.sortDir.field]) == 'number') {
                    if (_this.sortDir.dir == 'asc') {
                        return parseFloat(x[_this.sortDir.field]) - parseFloat(y[_this.sortDir.field]);
                    }
                    return parseFloat(y[_this.sortDir.field]) - parseFloat(x[_this.sortDir.field]);
                } else {
                    if (_this.sortDir.dir == 'asc') {
                        return x[_this.sortDir.field].localeCompare(y[_this.sortDir.field]);
                    }
                    return y[_this.sortDir.field].localeCompare(x[_this.sortDir.field]);
                }
            });
            this.store.isSort = true;
            this.render(this.store, true);
            delete this.store.map;
            this.createStoreMap();
        }
    },
    initComponent: function() {
        Chenxin.apply(this, {
            hasRowNumber: false,
            hasCheckBox: false,
            extensible: false,
            sortStyle: 'local',
            autoOddCls: false,
            addRowHoverCls: false,
            hasPage: false
        });
        Chenxin.UI.GroupReportGrid.superclass.initComponent.call(this);
    }
});

Chenxin.UI.ReportGrid=Chenxin.extend(Chenxin.UI.JsonGrid,{
	hasTotal:true,
	exportAble:true,
	hasPage:false,
	sortStyle:'local',
	totalCls:'x-expand-grid-total',
	render:function(data){	
		Chenxin.UI.ReportGrid.superclass.render.call(this,data);
		if(this.hasTotal&&data.rows.length&&!$('#'+this.renderTo+' .'+this.totalCls).length){
			var total={};
			for(var i=0;i<data.rows.length;i++){
				for(var c in data.rows[i]){
					if(!this.field[c]){
						continue;
					}
					if(total[c]==undefined){
						total[c]=0;
					}
					if(typeof(total[c])!='string'){
						if (this.field[c].captionCol ==true){//若此列为总计文本列
							total[c]='合计';
						}else{
							if(this.field[c].inTotal!=false){
								if (isNaN(data.rows[i][c])==true ||data.rows[i][c]==null) continue;
								total[c] += parseFloat(data.rows[i][c]);
								//.toFixed(2)
							}else{
								total[c]=' ';
							}
						}
						/*
						if(this.field[c].inTotal!=false){					
							total[c]+=parseFloat(data.rows[i][c]);
							if(isNaN(total[c])){
								total[c]='合计';
							}
						}else{
							total[c]=' ';
						}*/
					}
				}
			}
			for(var c in total){
				if (isNaN(total[c])==true || typeof(total[c])=='string') 
					continue;
				total[c] = total[c].toFixed(2);
			}
			var totalRow=this.createRow(total,data.rows.length);
			totalRow.addClass(this.totalCls);
			this.bodyDom.append(totalRow);	
			
			this.setBodyRowWidth();		
		}
	},
	initComponent:function(){		
		Chenxin.UI.ReportGrid.superclass.initComponent.call(this);
	}
});

/*
Chenxin.UI.Grid=Chenxin.extend(null,{
	columns:undefined,				//头部配置{a:{head:'abc',width:100,create:true,sortable:true}}
	param:{},						//查询参数
	baseParam:{},					//基础参数，不发生变化的参数，可以手动进行修改
	autoLoad:true,					//是否自动加载数据
	gridCls:'x-grid-main',			//表格样式
	headCls:'x-grid-head',			//头部样式
	selectCls:'x-grid-select',		//行选中样式
	hoverCls:'x-grid-hover',		//行滑过样式
	pageCls:'x-grid-page',			//分页工具条样式
	height:0,						//高度
	width:0,						//宽度
	gridWidth:0,					//内嵌数据table宽度
	hasCheckBox:true,				//有checkbox
	hasRowNumber:true,				//有行号
	hasPage:true,				//有分页
	pageIndex:0,					//当前页码
	pageSize:50,					//当前每页显示的记录条数
	colCount:0,						//列数
	sortField:'',					//排序字段
	id:'',							//ID
	renderTo:'',					//渲染的容器
	expertFileName:'数据导出',
	scope:this,
	expertFileName:'数据导出',	
	exportData:function(){
		Chenxin.Fn.exportToExcel(document.getElementById(this.renderTo).innerHTML,this.expertFileName);
	},
	createHead:function(){
		if(this.columns){
			var _tr=document.createElement('tr');
			_tr.className=this.headCls||'x-grid-head';
			this.headDom=$(_tr);
			var _this=this;
			
			if(this.hasRowNumber){				
				this.colCount+=1;
				this.headDom.append('<td style="width:20px;"> </td>');
			}
			if(this.hasCheckBox){
				this.colCount+=1;
				var _cab=document.createElement('input');
				_cab.type='checkbox';
				this.chkAll=$(_cab);
				this.chkAll.bind('click',function(){
					$('#'+_this.renderTo+' :input[name="chk_row"]').attr('checked',this.checked);
					if(this.checked){
						$('#'+_this.renderTo+' tr').addClass(_this.selectCls);
					}else{
						$('#'+_this.renderTo+' tr').removeClass(_this.selectCls);
					}
					
				});
				
				var _td=document.createElement('td');
				_td.style.width='10px';
				_td.style.textAlign='center';
				
				$(_td).append(this.chkAll);
				$(_td).appendTo(this.headDom);				
			}
			var _c=[];
			for(var c in this.columns){
				this.colCount+=1;
				_c.push(c);
				var _h=this.columns[c];
				var _td=document.createElement('td');
				_td.style.textAlign='center';
				$(_td).append($(document.createElement('span')).text(_h.head||''));
				
				if(_h.width){
					_td.style.width=_h.width+'px';
				}
				
				if(_h.create==false){
					_td.style.display='none';
				}
				_td.f=c;
				$(_td).bind('click',function(){
					_this.headSelect(this);
				});
				this.headDom.append(_td);
			}
			this.baseParam.field=_c.join(',');
			this.gridDom.append($(document.createElement('thead')).append(this.headDom));
			this.bodyDom=$(document.createElement('tbody'));
			this.gridDom.append(this.bodyDom);	

			if(this.gridWidth){
				this.gridDom.css('width',this.gridWidth+'px');
			}
		}
	},
	getSelectList:function(){
		if(!this.hasCheckBox){
			return '';
		}
		var idList=[];
		$('#'+this.renderTo+' :checked[name="chk_row"]').each(function(i){
			idList.push(this.id.substr(4));
		});
		return idList.join(',');
	},
	clear:function(){
		if(this.gridDom){
			this.bodyDom.empty();
		}else{
			this.el.empty();
		}
	},
	render:function(data){
		if(this.bodyDom){
			this.bodyDom.append(data.html||'<tr class="x-grid-row"><td style="text-align:center;" colspan="'+this.colCount+'">没有记录！</td></tr>');
		}else{
			this.el.prepend(data.data||data.html);
		}
		if((this.hasRowNumber||this.hasCheckBox)&&(data.count)){
			var _obj=this;
			$('#'+this.renderTo+' tr').each(function(i){
				if(!$(this).hasClass(_obj.headCls)){					
					if(_obj.hasCheckBox){
						$(this).prepend('<td style="text-align:center;"><input type="checkbox" id="chk_'+this.id+'" value="'+this.id+'" name="chk_row"/></td>');
					}
					if(_obj.hasRowNumber){
						$(this).prepend('<td style="text-align:center;" class="x-grid-row-head">'+(i+(_obj.pageSize*_obj.pageIndex))+'</td>');
						//$(this).prepend('<td style="text-align:center;">'+i+'</td>');
					}
				}
			});
		}
		if(this.hasPage){
			this.pageBar.reRender(data.count);
		}
		
	},
	createRowNum:function(){
		var _obj=this;
		$('#'+this.renderTo+' tr').each(function(i){
			if(!$(this).hasClass(_obj.headCls)){
				$(this).prepend('<td style="text-align:center;">'+i+'</td>');
			}
		});
	},
	load:function(){
		Chenxin.Msg.Loading.show();
		var _data={};
		Chenxin.apply(_data,this.param);
		Chenxin.apply(_data,this.baseParam);
		_data.sort=this.sortField;
		if(this.hasPage){
			_data.pageindex=this.pageIndex;
			_data.pagesize=this.pageSize;
		}
		
		var _this=this;
		Chenxin.ajax({ 
			type: 'get',
			dataType: 'html',
			url: this.actionUrl,
			data: _data,
			onSuccess: function(data,msg) {	
				if(_this.render){
					_this.render.call(_this,data);
				}
				if(_this.afterRender){
					_this.afterRender.call(_this,data,msg);
				}				
				Chenxin.Msg.Loading.hide();
			},
			onWrong:function(){	
				Chenxin.Msg.Loading.hide();						
			},
			onFail:function(){
				Chenxin.Msg.Loading.hide();
			},
			onError:function(){	
				Chenxin.Msg.Loading.hide();	
			}
		});
	},
	reload:function(param,pageIndex){
		this.param=param||this.param;
		this.clear();
		if(pageIndex!=undefined&&pageIndex>-1){
			this.pageIndex=pageIndex;
			if(this.pageBar){
				this.pageBar.pageIndex=this.pageIndex;
			}
		}
		this.load();
	},
	headSelect:function(el){
		if(!this.sortDir){
			this.sortDir={};
		}
		if(this.columns[el.f].sortable){
			$('.x-grid-sort-asc').removeClass('x-grid-sort-asc');
			$('.x-grid-sort-desc').removeClass('x-grid-sort-desc');
			if(this.sortDir[el.f]){
				if(this.sortDir[el.f]=='asc'){
					this.sortDir[el.f]='desc';
				}else{
					this.sortDir[el.f]='asc';
				}
			}else{
				this.sortDir[el.f]='asc';
			}
			this.sortDir[el.f]=this.sortDir[el.f];
			this.sortField=el.f+' '+this.sortDir[el.f];
			el.children[0].className='x-grid-sort-'+this.sortDir[el.f];
			this.reload();
		}
	},
	createPage:function(){
		if(this.hasPage){
			if(!this.pageBar){
				this.pageBar=new Chenxin.UI.PageBar({
					scope:this,
					pageSize:this.pageSize,
					pageIndex:this.pageIndex,
					pagingCb:function(){
						this.reload();
					}
				});
			}
		}
	},
	init:function(){
		if(this.height||this.width){
			if(this.height){
				this.el.css('height',this.height+'px');
			}
			
			if(this.width){
				this.el.css('width',this.width+'px');
			}
		}else{			
			this.el.css('overflow','auto');
			this.el.css('border-width','0px');
		}
		this.el.css('overflow','auto');
		this.el.addClass('x-grid-dom');
		
		if(this.columns){
			var tb=document.createElement('table');
			tb.className=this.gridCls||'x-grid-main';
			
			this.gridDom=$(tb);
			this.el.append(this.gridDom);
		}		
	},
	initEvent:function(){
		var _obj=this;
		var _tr=$('.x-grid-row');
		_tr.live('mouseover',function(){
			if($(this).hasClass(_obj.headCls)){
				return;
			}
			$(this).toggleClass(_obj.hoverCls);
			
		});
		_tr.live('mouseout',function(){
			if($(this).hasClass(_obj.headCls)){
				return;
			}
			$(this).toggleClass(_obj.hoverCls);			
		});
		_tr.live('click',function(e){
			if(e.target.tagName=='INPUT'){
				return;
			}
			if($(this).hasClass(_obj.headCls)){
				return;
			}
			if(_obj.scope){
				_obj.scope.currentId=this.id;
			}
			_obj.currentId=this.id;
						
			if(_obj.hasCheckBox){
				$('#'+_obj.renderTo+' :checked[name="chk_row"]').attr('checked',false);
				$('#chk_'+this.id).attr('checked',true);
			}
			
			$('.'+_obj.selectCls).removeClass(_obj.selectCls);
			$(this).toggleClass(_obj.selectCls);
			
			
			if(_obj.afterSelect){
				_obj.afterSelect.call(_obj.scope,this.id,this);
			}
		});
		$('#'+this.renderTo+' :input[name="chk_row"]').live('click',function(){
			$('#'+this.id.substr(4)).toggleClass(_obj.selectCls);
			if(_obj.scope){
				_obj.scope.currentId=this.id;
			}
			_obj.currentId=this.id;
		});
	},
	initComponent:function(){
		this.el=$('#'+this.renderTo);
		this.init();
		this.createHead();
		this.createPage();
		if(this.autoLoad){
			this.load();
		}
		this.initEvent();
	}
});
*/

Chenxin.UI.MultiGrid=Chenxin.extend(Chenxin.UI.Grid,{
	hasHead:true,						//是否有头部
	hasFoot:false,						//是否有底部
	expandAble:true,						//是否可以收起
	gridCls:'x-multigrid-main',			//表格样式
	selectCls:'x-multigrid-select',			//行选中样式
	hoverCls:'x-multigrid-hover',			//行滑过样式
	rowCls:'x-multigrid-row',				//行样式
	pageCls:'x-multigrid-page',				//分页工具条样式
	headCls:'x-multigrid-head',				//头部样式
	bodyCls:'x-multigrid-body',				//头部样式
	footCls:'x-multigrid-foot',				//头部样式
	collapseCls:'x-multigrid-collspse',	//收起样式
	expandCls:'x-multigrid-expand',	//展开样式
	sortItems:[{txt:'默认排序',val:''},{txt:'按时间升序',val:'addtime asc',icon:'x-sort-asc'},{txt:'按时间降序',val:'addtime desc',icon:'x-sort-desc'}],	
	btnConfig:[],
	getPageCount:function(count){
		return parseInt(count/this.pageSize)+(count%this.pageSize==0?0:1);
	},
	createHead:function(){
		if(this.hasHead&&!this.headDom){
			var _h=document.createElement('div');
			_h.className=this.headCls;
			var ih='<div class="x-multigrid-rc">共有<span id="'+this.id+'_rc" style="color:#ff0000;">0</span>条记录</div>';
			ih+='<div class="SelectWrapSingle" id="'+this.id+'_sf" style="margin-left:10px; margin-top:4px;"></div>';
			ih+='<dl class="x-multigrid-ps"><dt><input id="'+this.id+'_prev" type="button" name="btn_prev" title="上一页" class="x-multigrid-prev"/></dt><dt><span id="'+this.id+'_rcd">3/30</span></dt><dt><input id="'+this.id+'_next" type="button" name="btn_next" title="下一页" class="x-multigrid-next"/></dt></dl>';
			this.headDom=$(_h);
			this.headDom.append(ih);
			this.el.prepend(_h);
			
			var _this=this;

			this.sortCombo=new Chenxin.UI.Combo({
				containerId:'#'+this.id+'_sf',
				name:'sortField',
				items:this.sortItems,
				addPleaseSelected:false,
				colNum:1,
				colWidth:95,
				onSelected:function(){
					this.sortField=this.getValue();
					_this.reload();
				}
			});
		}		
	},
	createFoot:function(){
		if(this.hasFoot&&!this.footDom){
			var _f=document.createElemnt('div');
			_f.className=this.footCls;
			this.footDom=$(_f);
			this.el.append(_f);
		}
	},
	createBody:function(){
		if(!this.bodyDom){
			var _b=document.createElement('div');
			_b.className=this.bodyCls;
			this.bodyDom=$(_b);
			this.el.append(_b);			
		}	
	},
	init:function(){
		this.createBody();
		if(this.hasFoot){
			this.createFoot();
		}
		
		if(this.height){
			this.el.css('height',this.height+'px');
		}
		if(this.width){
			this.el.css('width',this.width+'px');
		}
		this.el.css('overflow','auto');
		this.el.addClass(this.gridCls);
	},
	reRenderHead:function(count){
		var pageCount=this.getPageCount(count);
		var filter='#'+this.id;
		$(filter+'_rc').html(count);
		$(filter+'_rcd').html((this.pageIndex+1)+'/'+pageCount);
		if(pageCount<=1){
			$(filter+'_prev')[0].className='x-multigrid-prev-disable';
			$(filter+'_next')[0].className='x-multigrid-next-disable';
		}else{
			if(this.pageIndex==0){
				$(filter+'_prev')[0].className='x-multigrid-prev-disable';	
				$(filter+'_next')[0].className='x-multigrid-next';		
			}else if(this.pageIndex==pageCount-1){
				$(filter+'_prev')[0].className='x-multigrid-prev';	
				$(filter+'_next')[0].className='x-multigrid-next-disable';			
			}else{
				$(filter+'_prev')[0].className='x-multigrid-prev';	
				$(filter+'_next')[0].className='x-multigrid-next';				
			}
		}
	},
	render:function(data){	
		if(this.bodyDom){
			this.bodyDom.append(data.html);
		}
		var h=this.bodyDom.find('ul').eq(0).find('li').eq(0).find('dl').length*25;
		this.bodyDom.find('ul').find('li').eq(0).css('height',h+'px');
		var _this=this;
		if(this.expandAble||this.hasCheckBox){
			this.bodyDom.find('ul').each(function(i){
				var _d=document.createElement('div');
				_d.className='x-multigrid-ce';
				
				if(_this.hasCheckBox){
					$(_d).append('<input id="chk_'+_this.id+'_'+this.id+'" name="chk_select" value="'+this.id+'" type="checkbox"/>');
				}
				if(_this.expandAble){
					$(_d).append('<span id="ce_'+this.id+'" title="展开" class="'+_this.collapseCls+'"></span>');
				}
				var _l=$(this).find('li');
				_l.eq(0).prepend(_d);
				_l.eq(1).css('margin-left','20px');
				_l.eq(1).css('margin-right','20px');
				//_l.eq(1).append('<div></div>');
			});
		}
		this.reRenderHead(data.count);
		if(this.hasPage){			
			this.pageBar.reRender(data.count);
		}
	},
	createBtn:function(){
	
	},
	clear:function(){
		this.bodyDom.empty();
	},
	initEvent:function(){		
		var filter='#'+this.id;
		var _this=this;
		$(filter+'_prev').live('click',function(){
			if(this.className=='x-multigrid-prev-disable'){
				return;
			}
			_this.pagIng(-1);
		});
		$(filter+'_next').live('click',function(){
			if(this.className=='x-multigrid-next-disable'){
				return;
			}
			_this.pagIng(1);
		});
		$('.'+this.collapseCls).live('click',function(){
			this.className=_this.expandCls;
			this.title='收起';
			$('#'+this.id.substr(3)).find('li').eq(1).slideDown();
		})
		$('.'+this.expandCls).live('click',function(){
			this.className=_this.collapseCls;
			this.title='展开';
			$('#'+this.id.substr(3)).find('li').eq(1).slideUp();
		});
		
		$('.'+this.rowCls).live('dblclick',function(){
			var _ce=$('#ce_'+this.id);
			if(_ce.hasClass(_this.collapseCls)){			
				$('#'+this.id).find('li').eq(1).slideDown();
				_ce[0].className=_this.expandCls;
				_ce[0].title='收起';
			}else{			
				$('#'+this.id).find('li').eq(1).slideUp();
				_ce[0].className=_this.collapseCls;
				_ce[0].title='展开';				
			}
			
			// this.className=_this.expandCls;
			// this.title='收起';
			// $('#'+this.id.substr(3)).find('li').eq(1).slideDown();
		});
		$('.'+this.rowCls).live('mouseover',function(){
			$(this).toggleClass(_this.hoverCls);
		});
		$('.'+this.rowCls).live('mouseout',function(){
			$(this).toggleClass(_this.hoverCls);
		})
	},
	pagIng:function(v){
		if(this.hasPage){
			this.pageBar.pageIndex+=v;
			this.pageBar.paging();
		}else{			
			this.pageIndex+=v;
			this.reload();
		}
	},
	initComponent:function(){
		delete this.hasRowNum;
		delete this.createRowNum;
		delete this.headSelect;
		Chenxin.UI.MultiGrid.superclass.initComponent.call(this);
	}
});

Chenxin.UI.LockGrid=Chenxin.extend(Chenxin.UI.Grid,{
	initComponent:function(){
		Cehnxin.UI.LockGrid.superclass.initComponent.call(this);
	}
});


Chenxin.UI.ContentGrid=Chenxin.extend(Chenxin.UI.JsonGrid,{
	extensible:false,
	contentField:'',
	autoOddCls:false,
	rowCls:'x-content-grid-row',
    selectCls:'x-content-grid-select', 	//行选中样式
	rowHeadCls:'x-content-grid-rowhead',
	rowContentCls:'x-content-grid-rowcontent',
	cellBorder:true,
	checkIsRowSelect:function(){
		return true;
	},
	renderer:function(){
		this.gridWidth=0;
		if(data.head){
			this.createHead(data.head);
		}
		
		this.bodyDom.empty();
		this.store=data;
		this.createStoreMap();
		if(!this.store.isSort&&this.sortDir.field&&this.sortStyle=='local'){
			this.sortRecord();
			return;
		}
		if (data.rows.length){
			if(data.rows){		
				for(var i=0;i<data.rows.length;i++){
					this.bodyDom.append(this.createRow(data.rows[i],i));
				}
			}else{
				Chenxin.UI.JsonGrid.superclass.render.call(this,data);
			}
		}else{
			this.bodyDom.append('<dl class="x-expand-grid-row"><dd style="width: '+this.el.width()+'px; text-align: center; border-right-width: 1px;">'+this.emptyText+'</dd></dl>');		
		}
		
		if(this.afterRender){
			this.afterRender.call(this,data);
		}
				
				
		this.setBodyRowWidth();
		if(this.ml){
			this.headDom.find('dl').css('margin-left',-this.ml+'px');
			this.bodyDom.scrollLeft(this.ml);
		}
		this.resetPageBar(data);
	},	
	createRow:function(row,index){
		var _dl=Chenxin.UI.ContentGrid.superclass.createRow.call(this,row,index);
		
		var _div=$(document.createElement('div'));
		_div.append(_dl);
		_dl.removeClass(this.rowCls);
		_width=0;
		if(this.hasNumber){
			_width+=21;
		}
		if(this.hasCheckBox){
			_width+=21;
		}
		_div.append('<p>'+row[this.contentField]+'</p>');
		_div.addClass(this.rowCls);
		_div[0].id=_dl[0].id;
		_dl[0].id='';
		return _div;
	}, 
	initComponent:function(){		
		Chenxin.UI.ContentGrid.superclass.initComponent.call(this);
	}
});


/**
*@description 树
*/
Chenxin.UI.Tree=Chenxin.extend(null,{
	actionUrl:'',
	renderTo:'',
	autoLoad:true,
	autoMask:true,
	currentNode:undefined,//当前选中节点，如果是多选，则为全部选中节点数组
	hasCheckBox:false,//是否有checkbox
	// isSelected:true,//区别展开
	levelCount:0,//总共多少层，
	txtField:'txt',
	valField:'val',
	title:'',
	store:[],
	height:400,
	width:200,
	showRoot:true,
	animation:true,//是否执行动画
	timelyLoad:false,//是否及时加载，即点击节点，就调用后台
	singleSelect:true,//选择模式,false为多选
	leafSelect:false,//只选择最底层子节点
	autoSelectChidren:true,//多选是，自动选择子节点
	hoverCls:'orgbgcolor',
	selectedCls:'selected_orgbgcolor',
	collapseCls:'x-closed-default',//收起样式
	expandCls:'x-open-default',//展开样式
	leafCls:'x-leaf-default',//叶节点样式
	titleCls:'x-title',
	onSelected:Chenxin.emptyFn,	//选中节点
	beforeExpand:Chenxin.emptyFn,//展开之前
	beforeReload:Chenxin.emptyFn,//重新加载之前
	param:{},
	/**
	*@description 检查是否添加Checkbox
	*@node 需要检查的节点
	*/
	checkAddChk:function(node){
		if(!node){
			return false;
		}
		if(this.hasCheckBox){//有Checkbox
			if(this.leafSelect){//只有叶节点能选择
				if(node.leaf){
					return true;
				}
				return false;
			}
			return true;
		}
		return false;
	},
	checkIsLeaf:function(items){
		if(!this.levelCount){
			return;
		}
		if(items.length){
			if(items[0].level==this.levelCount){
				this.setLeaf(items);
			}
		}
	},
	setLeaf:function(items){
		if(!items){
			return;
		}
		for(var i=0;i<items.length;i++){
			items[i].leaf=true;
		}
	},
	mask:function(){
		Chenxin.Msg.create({
			id:this.renderTo,
			dom:this.renderTo,
			opcity:10,
			icon:Chenxin.Msg.icon.cycle,
			content:'Loading...'
		});
	},
	unMask:function(){
		Chenxin.Msg.hide(this.renderTo);
	},
	load:function(fatherid){
		fatherid=fatherid||this.root[this.valField];
		fatherid=fatherid.replace(this.prex,'');		
			
		var father=this.findNodeById(fatherid);	
		
		if(father.leaf){
			return;
		}
		if(this.autoMask){
			this.mask();	
		}
		var data={op:'gettree',fatherid:fatherid};
		Chenxin.applyIf(data,this.param);
		Chenxin.ajax({
			url:this.actionUrl,
			data:data,			
			type: "get",
			dataType: "json",
			scope:this,
			onSuccess:function(data,msg){			
				if(!data.items.length){
					father.nochild=true;
					this.unMask();
					return;
				}
				for(var i=0;i<data.items.length;i++){
					if(!data.items[i].children){
						data.items[i].children=[];	
					}
					data.items[i].expand=false;
					data.items[i].fatherId=fatherid;
					data.items[i].level=father.level+1;
					//data.items[i].parentNode=father;
					this.store.push(data.items[i]);
				}
				father.children=data.items;
				
				if(this.checkIsLeaf){//叶节点前端判断
					this.checkIsLeaf.call(this,data.items);
				}
				
				this.render(data.items,father);
				
				if(this.autoMask){
					this.unMask();
				}
			}
		});
	},
	findParentNode:function(node){
		return this.findNodeById(node.fatherId);
	},
	findNodeById:function(id){
		id=id.replace(this.prex,'');
		for(var i=0;i<this.store.length;i++){
			if(this.store[i][this.valField]==id){
				return this.store[i];
			}
		}
		return null;
	},
	resetAllChk:function(domId){
		domId=domId||this.renderTo;
		$('#'+domId+' input:checked').each(function(){
			this.checked=false;
		});
	},
	initStore:function(){
		this.store=[];
		if(!this.root){
			this.root={};
			var rootId=(Math.random()*100000)+'';
			this.root[this.valField]=rootId.split('.')[0];
			this.root[this.txtField]='根节点';
		}
		if(!this.root.children){
			this.root.children=[];
		}
		this.root.expand=false;
		this.root.level=0;
		this.store.push(this.root);
	},
	init:function(){	
		this.bodyDom=$(document.createElement('div'));	
		if(this.height){
			this.dom.css('height',this.height+'px');
			this.bodyDom.css('height',this.height+'px');
		}
		
		if(this.width){
			this.dom.css('width',this.width+'px');	
			this.bodyDom.css('width',this.width+'px');	
		}
		this.dom.css('overflow','hidden');
		this.bodyDom.css('overflow','auto');
		
		//添加title
		if(this.title){
			this.dom.before('<div class="'+this.titleCls+'"><span class="'+this.titleCls+'-l" style="float:left"></span><span class="'+this.titleCls+'-m" style="float:left"><h2>'+this.title+'</h2></span><span class="'+this.titleCls+'-r " style="float:right"></span></div>');		
		}
		
		var cls=this.collapseCls;
		if(this.autoLoad){
			cls=this.expandCls;
			this.root.expand=true;
		}
		var addChk=this.checkAddChk(this.root);
		var _html='<ul>';		
		_html+='<li id="'+this.prex+this.root[this.valField]+'" '+(this.showRoot?'':'style="display:none;"')+'>';
		_html+='<span class="'+(!this.root.leaf?this.collapseCls:this.leafCls)+' x-tree-icon" id="ico_'+this.prex+this.root[this.valField]+'">&nbsp;</span>';//icon
		_html+=(addChk?'<input name="tree-check" type="checkbox" id="chk_'+this.prex+this.root[this.valField]+'"/>':'');//checkbox
		_html+='<span>'+this.root[this.txtField]+'</span>';//内容
		_html+='</li>';
		_html+='<ul>';
		this.bodyDom.append(_html);
		this.dom.append(this.bodyDom);
		this.dom.toggleClass('x-tree');
	},
	onClick:function(el){	
		var x=this.findNodeById(el.id);
		if(this.singleSelect){//单选
			if((this.leafSelect&&x.leaf)||!this.leafSelect){//只能选择叶节点
				if(x.select){
					$(el).removeClass(this.selectedCls);
					this.currentNode=undefined;
					x.select=false;//取出该节点已经被选中标记
				}else{
					$('#'+this.renderTo+' .'+this.selectedCls).removeClass(this.selectedCls);
					$(el).addClass(this.selectedCls);
					if(this.currentNode){
						this.currentNode.select=false;					
					}
					this.currentNode=x;
					x.select=true;//标记该节点已经被选中
				}
				if(this.hasCheckBox){
					this.resetAllChk();
					$('#chk_'+el.id).attr('checked',x.select);
				}
			}
		}else{//多选		
			var _c=$('#chk_'+el.id);
			if((this.leafSelect&&x.leaf)||!this.leafSelect){//只能选择叶节点
				if(x.select){//已经勾选上了，说明已经是选中的，则进行移除
					_c.attr('checked',false);
					$(el).removeClass(this.selectedCls);
					this.currentNode.remove(x);
					x.select=false;
				}else{
					$(el).addClass(this.selectedCls);
					this.currentNode.push(x);
					x.select=true;
				}
				$('#chk_'+el.id).attr('checked',x.select);
				
				if(this.autoSelectChidren&&x.children&&x.children.length){//是否自动选择孩子节点
					this.childrenSelect(x,x.select);
				}
			}
		}
		if(this.onSelected){
			this.onSelected.call(this,x,el);
		}
	},
	/**
	*@description 操作孩子节点选中
	*@node 需要操作的节点
	*@select 是需要选中，还是需要删除
	*/
	childrenSelect:function(node,select){
		for(var i=0;i<node.children.length;i++){
			if(select){//选中
				if(!node.children[i].select){				
					this.currentNode.push(node.children[i]);
					$('#'+this.prex+node.children[i][this.valField]).addClass(this.selectedCls);
					
				}
			}else{//删除			
				this.currentNode.remove(node.children[i]);
				$('#'+this.prex+node.children[i][this.valField]).removeClass(this.selectedCls);
			}
			node.children[i].select=select;
			$('#chk_'+this.prex+node.children[i][this.valField]).attr('checked',select);
			if(node.children[i].children&&node.children[i].children.length){
				this.childrenSelect(node.children[i],select);
			}
		}
	},
	expandNode:function(node){
		if(!node.nochild){	//有孩子节点	
			var _id=this.prex+node[this.valField];
			if(this.beforeExpand){
				this.beforeExpand.call(this,node);
			}
			if($('#_'+_id).length){//已经存在					
				if(this.timelyLoad){//是否及时
					this.load(_id);							
				}else{
					if(this.animation){
						$('#_'+_id).slideDown("fast");
					}else{
						$('#_'+_id).show();
					}
				}
			}else{
				this.load(_id);
			}
		}
		node.expand=true;
	},
	collapseNode:function(node){
		if(!node.nochild){//有孩子节点
			var _id=this.prex+node[this.valField];
			if(this.animation){
				$('#_'+_id).slideUp('fast');
			}else{
				$('#_'+_id).hide();
			}
		}
	
		node.expand=false;
	},
	initEvent:function(){
		var _this=this;
		var filter='#'+this.renderTo+' li';
		$(filter).live('click',function(e){
			if($(e.target).hasClass('x-tree-icon')){//点击图标，不触发onClick事件
				return;
			}
			
			_this.onClick(this);
		});
		
		$(filter+' .x-tree-icon').live('click',function(){
			if(!$(this).hasClass('x-tree-icon')){//非展开按钮，直接返回
				return;
			}
			
			var x=_this.findNodeById(this.id.substr(4));
			
			if(x.leaf){
				return;
			}
			
			if(x.expand){
				_this.collapseNode(x);				
				$(this).removeClass(_this.expandCls);
				$(this).addClass(_this.collapseCls);
			}else{
				_this.expandNode(x);
				$(this).removeClass(_this.collapseCls);
				$(this).addClass(_this.expandCls);
			}
			
			_this.resetSize();
		});
		
		$(filter).live('mouseover',function(){			
			$(this).toggleClass(_this.hoverCls);
		});
		$(filter).live('mouseout',function(){
			$(this).toggleClass(_this.hoverCls);
		});
		this.bodyDom.scroll(function(){
			if(_this.scrollBodyDom){
				_this.scrollBodyDom.call(_this,this);
			}
		});
	},
	scrollBodyDom:Chenxin.emptyFn,
	render:function(items,fatherNode){
		var nodeList='';
		
		$('#_'+this.prex+fatherNode[this.valField]).remove();
		if(items.length){
			var addChk=this.checkAddChk(items[0]);
			var _indent=items[0].level*15;
			if(!this.showRoot){
				_indent-=15;
			}
			for(var i=0;i<items.length;i++){
				nodeList+='<li id="'+this.prex+items[i][this.valField]+'" style="text-indent:'+_indent+'px">';
				nodeList+='<span class="'+(!items[i].leaf?this.collapseCls:this.leafCls)+' x-tree-icon" id="ico_'+this.prex+items[i][this.valField]+'">&nbsp;</span>';//icon
				nodeList+=(addChk?'<input name="tree-check" type="checkbox" id="chk_'+this.prex+items[i][this.valField]+'"/>':'');//checkbox
				nodeList+='<span>'+items[i][this.txtField] + ((items[i].type=='700')?('('+ items[i].code+')'):'') +'</span>';//内容
				nodeList+='</li>';		
			}
			nodeList='<ul id="_'+this.prex+fatherNode[this.valField]+'" '+(this.animation?'style="display:none;"':'')+'>'+nodeList+'</ul>';
			$('#'+this.prex+items[0].fatherId).after(nodeList);
			
			if(this.animation){
				$('#_'+this.prex+items[0].fatherId).slideDown("fast");
			}			
		}
		if(this.afterRender){
			this.afterRender(items);
		}
	},
	resetSize:function(){		
		var w=document.getElementById(this.renderTo).clientWidth;
		$('#'+this.perx+this.renderTo+' ul').each(function(i){
			$(this).css('width',w+'px');
		});
	},
	reload:function(node){
		if(!node){
			node=this.root;
		}
		if(!node[this.valField]){
			return;
		}
		this.removeChildrenNode(node);
		//alert($('#_'+this.prex+node[this.valField]).length);
		$('#_'+this.prex+node[this.valField]).remove();
		if(this.beforeReload){
			this.beforeReload.call(this,node);
		}
		this.load(node[this.valField]);
	},
	removeChildrenNode:function(node){
		if(!node){
			return;
		}
		for(var i=0;i<node.children.length;i++){
			this.removeChildrenNode(node.children[i]);
			this.store.remove(node.children[i]);
		}
	},
	createPrex:function(){
		var _p='cx_'+(Math.random()*1000000);
		_p+='_';
		_p=_p.replace('.','');
		return _p;
	},
	initComponent:function(){
		if(!this.renderTo){
			throw new Error('renderTo is need!');
		}
		this.dom=$('#'+this.renderTo);
		this.prex=this.createPrex();
		
		
		if(!this.singleSelect){//多选
			this.hasCheckBox=true;//多选默认有Checkbox
			this.currentNode=[];
		}
		
		this.initStore();
		this.init();
		
		if(this.autoLoad){
			this.load();
		}
		this.initEvent();
		
	}
});

/**
*@description 树Grid
*/
Chenxin.UI.TreeGrid=Chenxin.extend(Chenxin.UI.Tree,{
	collapseCls:'x-closed-folder',//收起样式
	expandCls:'x-open-folder',//展开样式
	leafCls:'x-leaf-folder',//叶节点样式
	render:function(items){
		var nodeList='';
		if(items.length){
			var addChk=this.checkAddChk(items[0]);
			var _indent=items[0].level*15;
			if(!this.showRoot){
				_indent-=15;
			}
			for(var i=0;i<items.length;i++){
				nodeList+='<li id="'+this.prex+items[i][this.valField]+'" style="text-indent:'+_indent+'px">';
				
				for(var j=0;j<this.column.length;j++){
					var _dd='<dd style="width:'+this.column[j].width+'px;';
					if(j==0){
						_dd+='text-indent:'+_indent+'px;">';
						_dd+='<span class="'+(!items[i].leaf?this.collapseCls:this.leafCls)+' x-tree-icon" id="ico_'+this.prex+items[i][this.valField]+'">&nbsp;</span>';//icon
						_dd+=(addChk?'<input name="tree-check" type="checkbox" id="chk_'+this.prex+items[i][this.valField]+'"/>':'');//checkbox
					}else{
						_dd+='text-indent:0px;text-align:center;">';					
					}
					_dd+='<span>'+(items[i][this.column[j].name]||'')+'</span>';
					_dd+='</dd>';
					
					nodeList+=_dd;
				}
				nodeList+='<dd style="clear:both; display:none"></dd>'				
				
				nodeList+='</li>';	
			}
			nodeList='<ul id="_'+this.prex+items[0].fatherId+'" '+(this.animation?'style="display:none;"':'')+'>'+nodeList+'</ul>';
			$('#'+this.prex+items[0].fatherId).after(nodeList);
			
			if(this.animation){
				$('#_'+this.prex+items[0].fatherId).slideDown("fast");
			}			
		}
		if(this.afterRender){
			this.afterRender(items);
		}
		this.initWidth();
	},
	createHead:function(column){
		column=column||this.column;
		if(column.length){
			var _ul=document.createElement('ul');
			_ul.className='x-tree-header';

			for(var i=0;i<column.length;i++){
				var _li=document.createElement('li');
				if(!column[i].create){
					_li.style.display='none';
				}
				_li.innerHTML=column[i].header;
				_li.style.width=(column[i].width||100)+'px';
				_li.style.height='25px';
				$(_ul).append(_li);
			}
			
			this.headDom=$(document.createElement('div'));
			this.headDom.append(_ul);
			this.dom.prepend(this.headDom);
			this.dom.css('border-top-width','0px');
		}
	},
	initWidth:function(){
		var _width=this.dom.width();
		
		var _w=0;
		for(var i=0;i<this.column.length;i++){
			if(this.column[i].create){
				_w+=(this.column[i].width||100);
			}
		}
		
		if(_width<_w){
			this.dom.css('width',_width+'px');
			this.bodyDom.css('height',(this.dom.height()-25)+'px');
			$('#'+this.renderTo+' ul').each(function(){
				$(this).css('width',(_w+30)+'px');
			});
			this.headDom.find('ul').css('width',(_w+50)+'px');
		}else{			
			this.bodyDom.css('height',(this.dom.height()-28)+'px');
		}
	},
	scrollBodyDom:function(el){
		this.headDom.css('margin-left',-el.scrollLeft+'px');
	},
	initComponent:function(){
		Chenxin.UI.TreeGrid.superclass.initComponent.call(this);
		this.createHead();
	}
});

/**
*@description 树形选择窗体
*/
Chenxin.UI.TreeCombo=Chenxin.extend(Chenxin.UI.Tree,{
	textBoxId:'',
	autoMask:false,
	autoLoad:false,
	width:250,
	height:200,
	hasCheckBox:true,
	isShow:false,
	_oldNode:undefined,
	inModelType:'val',//val,txt,all
	txtModelName:'',//TxtModelName
	name:'',
	showRoot:false,
	elCls:'x-input-tree',
	collapseCls:'x-closed-folder',//收起样式
	expandCls:'x-open-folder',//展开样式
	leafCls:'x-leaf-folder',//叶节点样式
	intervalAutoHide:null,
	comboType:'treecombo',//combo类型
	value:'',
	text:'',
	required:false,
	afterSetValue:Chenxin.emptyFn,//在设置值之后触发的时间，默认传递函数val,txt
	initValidator: function() {
		if(!$('#'+this.textBoxId+'Tip').length){
			$('#'+this.textBoxId).after('<div id="' + this.textBoxId + 'Tip" style="float:left; margin-left: 5px; width: 50px; height: 26px; line-height: 26px; text-align: left; display:none" class="onError fl">请选择！</div>');		
		}
    },
    resetValidator:function(){
		if(this.required){
			$('#' + this.textBoxId + 'Tip').hide();			
		}
	},
	validator: function() {
		if(this.value){
			return true;
		}
        if (!this.required) {
			$('#' + this.textBoxId + 'Tip').hide();
            return true;
        }
		this.initValidator();
		if(this.singleSelect){//单选
			if(!this.currentNode){
				$('#' + this.textBoxId + 'Tip').show();
				return false;			
			}else{
				$('#' + this.textBoxId + 'Tip').hide();
				return true;
			}
		}else{//多选		
			if(!this.currentNode.length){
				$('#' + this.textBoxId + 'Tip').show();
				return false;			
			}else{
				$('#' + this.textBoxId + 'Tip').hide();
				return true;
			}
		}
        return true;
    },
	createSearch:Chenxin.emptyFn,
	getCurrentVal:function(cnList){
		return this.getCurrentV(this.valField,cnList);	
	},
	getCurrentTxt:function(cnList){
		return this.getCurrentV(this.txtField,cnList);
	},
	getCurrentV:function(field,cnList){		
		var _v='';
		cnList=cnList||this.currentNode;
		if(this.singleSelect){
			_v=cnList[field];
		}else{
			for(var i=0;i<cnList.length;i++){
				_v+=cnList[i][field]+',';
			}
			if(_v){
				_v=_v.substr(0,_v.length-1);
			}
		}
		return _v;			
	},
	afterRender:function(items){
		if(!this.value){
			return;
		}
		if(this.leafSelect){//页节点可选，只判断叶节点
			if(items.length&&items[0].leaf){//是叶节点并且有节点
				this.setCheckByValue(items);
			}
		}else{
			this.setCheckByValue(items);	
		}
	},
	setCheckByValue:function(items,value){
		value=value||this.value;		
		items=items||this.store;
		var filter='';
		if(items.length){//有节点
			if(this.singleSelect){//单选
				for(var i=0;i<items.length;i++){
					if(items[i][this.valField]==value){
						filter='#chk_'+this.prex+value;
						items[i].select=true;
						this.currentNode=items[i];
						break;
					}
				}
			}else{//多选
				var _v=','+value+',';
				var _idList=[];
				for(var i=0;i<items.length;i++){
					if(_v.indexOf(','+items[i][this.valField]+',')!=-1){	
						_idList.push('#chk_'+this.prex+items[i][this.valField]);
						items[i].select=true;
						this.currentNode=this.currentNode||[];
						this.currentNode.push(items[i]);
					}
				}
				filter=_idList.join(',');
			}
		}
		
		if(filter){
			$(filter).attr('checked','checked');
		}
	},
	getValue:function(){
		if(this.currentNode){//选过节点
			return this.getCurrentVal();
		}
		return this.value;
	},
	getText:function(){
		if(this.currentNode){//选过节点
			return this.getCurrentTxt();
		}
		return this.text;		
	},	
	setValue:function(val,txt){
		this.value=val;
		this.setText(txt);		
		
		if(this.afterSetValue){
			this.afterSetValue.call(this,val,txt);
		}
	},
	setDefValue:function(){
		this.value='';
		this.text='';
		this.el.val('');
	},
	setText:function(txt){
		if(txt){
			this.text=txt;
			this.el.val(txt);
			return;
		}
		var _this=this;
		var _data={op:'gettext',val:this.value};
		Chenxin.apply(_data,this.param);
		Chenxin.ajax({
			url:this.actionUrl,
			data:_data,
			type:'get',
			onSuccess:function(data,msg){
				_this.text=data.txt;
				_this.el.val(data.txt);
			}
		});
		
	},
	initCombo:function(){
		this.el.attr('readonly','readonly');
		
		//创建Table
		var _t=document.createElement('table');
		_t.className='x-tree-combo-tab';
		_t.id='tab-'+this.renderTo;
		_t.style.display='none';
		_t.style.width=this.width+'px';
		
				
		if(this.createSearch){
			var _sp=this.createSearch();
			_sp='<span style="padding-left:5px;">查询条件：</span>'+_sp;
			$(_t).append($(document.createElement('tr')).append($(document.createElement('td')).attr('id','sp_'+this.renderTo).append(_sp)));
		}
		$(_t).append($(document.createElement('tr')).append(document.createElement('td')));
		$(_t).append($(document.createElement('tr')).append($(document.createElement('td')).css('text-align','center')));
		$(document.body).append($(_t));
		
		//创建确定按钮
		var _s=document.createElement('input');
		_s.type='button';
		_s.value='确定';
		_s.id='bbar-sure-'+this.renderTo;
		_s.title='确定';
		_s.style.marginRight='10px';
		_s.className='x-tree-combo-btn';
		this.bbarSure=$(_s);
		$('#tab-'+this.renderTo+' td:last').append($(_s));
		
		//创建取消按钮
		var _c=document.createElement('input');
		_c.type='button';
		_c.value='取消';
		_c.id='bbar-cancle-'+this.renderTo;
		_c.title='取消';
		_c.style.marginLeft='10px';
		_c.style.marginRight='10px';
		_c.className='x-tree-combo-btn';
		this.bbarCancle=$(_c);
		$('#tab-'+this.renderTo+' td:last').append($(_c));
		
		
		//创建重置按钮
		var _r=document.createElement('input');
		_r.type='button';
		_r.value='重置';
		_r.id='bbar-reset-'+this.renderTo;
		_r.title='重置';
		_r.style.marginLeft='10px';
		_r.className='x-tree-combo-btn';
		this.bbarReset=$(_r);
		$('#tab-'+this.renderTo+' td:last').append($(_r));
		
		//创建树容器
		var _d=document.createElement('div');
		_d.id=this.renderTo;
		_d.style.width=this.width+'px';
		_d.style.height=this.height+'px';
		_d.className='x-tree-combo';
		if(this.createSearch){		
			$('#tab-'+this.renderTo+' td:eq(1)').append($(_d));
		}else{		
			$('#tab-'+this.renderTo+' td:first').append($(_d));
		}
		
		
		var intervalHide=null;
		var _this=this;	
		
		$(_t).bind('mouseleave',function(){	
			if(_this.isShow){			
				intervalHide=setTimeout(function(){
					_this.setChkByOldNode();
					_this.show(false);
				},200);
			}
		});
		
		$(_t).bind('mouseenter',function(){	
			if(_this.intervalAutoHide){
				clearTimeout(_this.intervalAutoHide);
			}
			if(intervalHide!=null){
				clearTimeout(intervalHide);
			}
		});
	},
	beforeExpand:function(node){
		if(this.createSearch){
			var _p=Chenxin.Fn.getFormJson('sp_'+this.renderTo);
			Chenxin.apply(this.param,_p);
		}
	},
	initEvent:function(){
		var _this=this;		
		$('#bbar-sure-'+this.renderTo).live('click',function(){
			_this.sure();
		});
		$('#bbar-cancle-'+this.renderTo).live('click',function(){
			_this.cancle();
		});
		$('#bbar-reset-'+this.renderTo).live('click',function(){
			_this.reset();
		});
		
		this.el.click(function(){
			
			if(!_this.autoLoad&&_this.store.length==1){//不在实例化的时候，加载数据，而在第一次点击的时候，加载数据
				_this.load();
			}
			if(_this.singleSelect){//单选
				_this._oldNode=_this.currentNode;
			}else{
				if(!_this.oldNode){
				
				}
				_this._oldNode=[];
				for(var i=0;i<_this.currentNode.length;i++){
					_this._oldNode.push(_this.currentNode[i]);
				}
			}
			_this.show(true);
		});
		
		// this.el.blur(function(){
			// _this.intervalAutoHide=setTimeout(function(){
				// _this.setChkByOldNode();
				// _this.show(false);
			// },200);
		// });
		Chenxin.UI.TreeCombo.superclass.initEvent.call(this);
	},
	show:function(isShow){
		if(isShow==undefined){	
			isShow=!this.isShow;
		}
		if(this.disable&&isShow){
			return;
		}
				
		var _tab=$('#tab-'+this.renderTo);
		if(isShow){		
			var offset=this.el.offset();
			_tab.css('left',offset.left+'px');
			
			if(_tab.height()+offset.top+this.el.innerHeight()>document.body.clientHeight){
				_tab.css('top',offset.top-_tab.height());
			}else{
				_tab.css('top',offset.top+this.el.innerHeight()+'px');
			}
			//_tab.css('top',offset.top+this.el.innerHeight()+'px');
			
			// _tab.slideDown('fast');
			_tab.show();
			// var _this=this;
			// this.intervalAutoHide=setTimeout(function(){
				// _this.setChkByOldNode();
				// _this.show(false);
			// },1000);
		}else{			
			// _tab.slideUp('fast');
			_tab.hide();
			//setTimeout(function(){_tab.hide();},2000);
		}
		this.isShow=isShow;	
	},
	sure:function(){
		if(this.currentNode){
			this.el.val(this.getCurrentTxt());
		}else{
			this.el.val('');
		}
		
		this.show(false);
	},
	cancle:function(){
		
		this.setChkByOldNode();
		this.show(false);
	},
	reset:function(){
		this.value=undefined;
		
		this.el.val('');
		this.resetAllChk();
		if(this.singleSelect){
			this.currentNode=undefined;
		}else{
			this.currentNode=[];
		}
		this.show(false);
	},
	setDisable:function(){
		this.disable=true;
		this.el.disable();
	},
	setEnable:function(){
		this.disable=false;	
		this.el.enable();
	},
	setChkByOldNode:function(){
		if(this.currentNode!=this._oldNode){
			this.currentNode=this._oldNode;		
			this.resetAllChk();
						
			if(this.singleSelect){				
				if(this._oldNode){
					$('#chk_'+this.prex+this._oldNode[this.valField]).attr('checked','checked');				
				}else if(this.value){
					$('#chk_'+this.prex+this.value).attr('checked','checked');					
				}
			}else{
				for(var i=0;i<this.currentNode.length;i++){
					$('#chk_'+this.prex+this.currentNode[i][this.valField]).attr('checked','checked');					
				}
				if(!this.currentNode&&this.value){
					$('#chk_'+this.prex+this.value.replace(',',',#chk_')).attr('checked','checked');					
				}
			}
		}
	},
	initComponent:function(){
		this.el=$('#'+this.textBoxId);
		this.el.addClass(this.elCls);
		this.renderTo='tree-'+this.textBoxId;
		this.title='';
		this.initCombo();
		if(!this.singleSelect){
			this._oldNode=[];
		}
		if(!this.name){
			this.name=this.textBoxId;
		}
		
		Chenxin.UI.TreeCombo.superclass.initComponent.call(this);
		if (this.required) {
            this.initValidator();
        }
	}
        
});

/**
*@description 组织结构树形选择下拉框
*/
Chenxin.UI.OrganizationTreeCombo=Chenxin.extend(Chenxin.UI.TreeCombo,{	
	actionUrl:'/service/OrganizationTreeCombo.ashx',
	leafSelect:true,
	param:{type:0},
	root:{
		val:'00000000-0000-0000-0000-000000000000',
		txt:'易居臣信',
		type:'0'
	},
	beforeExpand:function(node){
		this.param.type=node.type;
		Chenxin.UI.OrganizationTreeCombo.superclass.beforeExpand.call(this,node);
	},
	initComponent:function(){
		Chenxin.UI.OrganizationTreeCombo.superclass.initComponent.call(this);
	}
});

/**
*@description 部门树形下拉选择框
*/
Chenxin.UI.DepartTreeCombo=Chenxin.extend(Chenxin.UI.OrganizationTreeCombo,{	
	checkIsLeaf:function(items){
		if(items.length){
			if(items[0].type=='500'||items[0].type=='600'){
				for(var i=0;i<items.length;i++){
					items[i].leaf=true;
				}
			}
		}				
	},
	setText:function(txt){
		if(txt){
			this.text=txt;
			this.el.val(txt);
			return;
		}
	    this.param.txttype = 'depart';
		Chenxin.UI.DepartTreeCombo.superclass.setText.call(this);
	},
	initComponent:function(){
		Chenxin.UI.DepartTreeCombo.superclass.initComponent.call(this);	
	}
});

/**
*@description 人员树形下拉选择框
*/
Chenxin.UI.UserTreeCombo=Chenxin.extend(Chenxin.UI.OrganizationTreeCombo,{	
	hasSearch:true,//是否有查询条件
	checkIsLeaf:function(items){
		if(items.length){
			if(items[0].type=='700'){
				for(var i=0;i<items.length;i++){
					items[i].leaf=true;
				}
			}
		}				
	},
	createSearch:function(){
		return '<input type="radio" name="status" value="1" id="r_'+this.prex+this.renderTo+'_at" checked="checked"/><label for="r_'+this.prex+this.renderTo+'_at">在职</label>'+'<input type="radio" name="status" value="-1" id="r_'+this.prex+this.renderTo+'_lv"/><label for="r_'+this.prex+this.renderTo+'_lv">离职</label>'
	},	
	setText:function(txt){
		if(txt){
			this.text=txt;
			this.el.val(txt);
			return;
		}
		this.param.txttype='user';
		Chenxin.UI.UserTreeCombo.superclass.setText.call(this);
	},
	initEvent:function(){
		var _this=this;
		$('#sp_'+this.renderTo+' input[name="status"]').live('click',function(){
			_this.param.status=this.value;
			_this.param.type=0;
			_this.reload();
		});
		Chenxin.UI.UserTreeCombo.superclass.initEvent.call(this);
	},
	initComponent:function(){
		this.param.status=1;
		if(!this.hasSearch){
			this.createSearch=undefined;
		}
		Chenxin.UI.UserTreeCombo.superclass.initComponent.call(this);	
	}
});

/**
*@description 有简单，快捷选择模式的属性选择框
*/
Chenxin.UI.RichModelTreeCombo=Chenxin.extend(Chenxin.UI.UserTreeCombo,{
	activeIndex:0,//当前有快速,0为快速选择，1为详细选择
	valueIndex:1,//当前是否是快速选择选中,0为快速选择，1为详细选择
	validator:function(){
	
		if(!this.valueIndex){					
			if (!this.required) {
				$('#' + this.textBoxId + 'Tip').hide();
				return true;
			}
			this.initValidator();
			
			if(this.value){
				return true;
			}
			
			if(this.singleSelect){//单选
				if(!this.qcNode){
					$('#' + this.textBoxId + 'Tip').show();
					return false;			
				}else{
					$('#' + this.textBoxId + 'Tip').hide();
					return true;
				}
			}else{//多选		
				if(!this.qcNode.length){
					$('#' + this.textBoxId + 'Tip').show();
					return false;			
				}else{
					$('#' + this.textBoxId + 'Tip').hide();
					return true;
				}
			}
			return true;
		}else{
			return Chenxin.UI.RichModelTreeCombo.superclass.validator.call(this);
		}
	},
	createModel:function(){
		var _ul=document.createElement('ul');
		_ul.className='x-tree-tabs';
		_ul.style.width=this.width+'px';
		_ul.id='tabsmenu_'+this.renderTo;
		var _qli=document.createElement('li');
		_qli.innerHTML='快捷模式';
		_qli.className='x-tree-tab-active';
		$(_ul).append(_qli);
		var _dli=document.createElement('li');
		_dli.innerHTML='标准模式';
		_dli.className='x-tree-tab-numal';
		$(_ul).append(_dli);
		
		var _this=this;
		$(_qli).click(function(){
			$('#'+_this.renderTo).hide();
			$('#qmodel_'+_this.renderTo).show();
			_qli.className='x-tree-tab-active';
			_dli.className='x-tree-tab-numal';
			_this.activeIndex=0;
		});
		
		$(_dli).click(function(){
			$('#'+_this.renderTo).show();
			$('#qmodel_'+_this.renderTo).hide();
			_dli.className='x-tree-tab-active';
			_qli.className='x-tree-tab-numal';
			_this.activeIndex=1;
		});
		
		$('#'+this.renderTo).before(_ul);
	},
	createQuickDiv:function(){
		this.dom.before('<div id="qmodel_'+this.renderTo+'" class="x-tree-qmodel" style="height:'+this.height+'px;overflow:auto;"></div>');
		this.dom.hide();
	},
	loadUser:function(fatherid,type){
		if(!fatherid){
			return;
		}
		this.fatherid=fatherid;
		var data={op:'getdepartuser',fatherid:fatherid};
		var _p=Chenxin.Fn.getFormJson('sp_'+this.renderTo);
		Chenxin.apply(this.param,_p);
		Chenxin.apply(data,this.param);
		Chenxin.ajax({
			url:this.actionUrl,
			data:data,			
			type: "get",
			dataType: "json",
			scope:this,
			onSuccess:function(data,msg){
				this.qStore=data.items;
				this.renderUser(data.items);				
			}
		});
	},
	clearUserItems:function(){
		$('#qmodel_'+this.renderTo+' ul').text('');
	},
	renderUser:function(items){
		var _ul=$('#qmodel_'+this.renderTo+' ul');
		if(!_ul.length){
			_ul=$(document.createElement('ul'));
			$('#qmodel_'+this.renderTo).append(_ul);
		}else{
			_ul.text('');
		}
		
		for(var i=0;i<items.length;i++){
			_ul.append('<li id="qli_'+items[i][this.valField]+'"><span class="x-leaf-folder-icon"></span><input id="qchk_'+this.prex+items[i][this.valField]+'" value="'+items[i][this.valField]+'" name="chk_val" type="checkbox"/><span>'+items[i][this.txtField]+'('+items[i].code+')'+'</span></li>');
		}
	},
	sure:function(){
		if(this.qStore.length){//有快速
			if(this.activeIndex==0){//当前为快速，且有选中
				if(this.qcNode){
					this.el.val(this.getCurrentTxt(this.qcNode));				
				}else{
					this.el.val('');
				}
				this.show(false);
				this.valueIndex=0;
			}else{
				this.valueIndex=1;
				Chenxin.UI.RichModelTreeCombo.superclass.sure.call(this);
			}
		}else{
			this.valueIndex=1;
			Chenxin.UI.RichModelTreeCombo.superclass.sure.call(this);
		}
	},
	getValue:function(){
		if(!this.valueIndex){
			if(this.qcNode){
				return this.getCurrentVal(this.qcNode);				
			}else{
				return this.value;
			}
		}else{
			return Chenxin.UI.RichModelTreeCombo.superclass.getValue.call(this);
		}
	},
	getText:function(){
		if(!this.valueIndex){
			if(this.qcNode){
				return this.getCurrentTxt(this.qcNode);				
			}else{
				return this.text;
			}
		}else{
			return Chenxin.UI.RichModelTreeCombo.superclass.getText.call(this);
		}		
	},
	reset:function(){
		if(this.qcNode){
			this.qcNode=this.singleSelect?undefined:[];
			$('#qmodel_'+this.renderTo).find('input').removeAttr('checked');
		}
		Chenxin.UI.RichModelTreeCombo.superclass.reset.call(this);
	},
	show:function(){
		Chenxin.UI.RichModelTreeCombo.superclass.show.apply(this,arguments);
		if(this.isShow){
			var _a=$('#tabsmenu_'+this.renderTo+' li');
			if(!this.qStore.length){//快速搜索没有
				if(this.activeIndex==1){
					return;
				}
				$('#qmodel_'+this.renderTo).hide();
				this.dom.show();
				$(_a[0]).removeClass('x-tree-tab-active');
				$(_a[0]).addClass('x-tree-tab-numal');
				
				$(_a[1]).removeClass('x-tree-tab-numal');
				$(_a[1]).addClass('x-tree-tab-active');
				this.activeIndex=1;
			}else{
				if(this.activeIndex==0){
					return;
				}
				$('#qmodel_'+this.renderTo).show();
				$('#'+this.renderTo).hide();
				$(_a[1]).removeClass('x-tree-tab-active');
				$(_a[1]).addClass('x-tree-tab-numal');
				
				$(_a[0]).removeClass('x-tree-tab-numal');
				$(_a[0]).addClass('x-tree-tab-active');	
				this.activeIndex=0;		
			}
		}
	},
	findQNode:function(id){
		id=id.replace('qli_','');
		for(var i=0;i<this.qStore.length;i++){
			if(this.qStore[i][this.valField]==id){
				return this.qStore[i];
			}
		}
		return null;
	},
	initEvent:function(){
		var _this=this;
		$('#qmodel_'+this.renderTo+' li').live('mouseover',function(){
			$(this).toggleClass(_this.hoverCls);
		});
		$('#qmodel_'+this.renderTo+' li').live('mouseout',function(){
			$(this).toggleClass(_this.hoverCls);
		});
		
		$('#qmodel_'+this.renderTo+' li').live('click',function(){
			if(_this.singleSelect){
				_this.resetAllChk('#qmodel_'+_this.renderTo);
			}
			var _chk=$('#qchk_'+_this.prex+this.id.replace('qli_',''));
			if(_this.singleSelect){
				_chk.attr('checked','checked');
			}
			if(_chk.attr('checked')){//选中
				if(_this.singleSelect){//单选
					_this.qcNode=_this.findQNode(this.id);
				}else{
					_this.qcNode.push(_this.findQNode(this.id));
				}				
			}else{
				if(_this.singleSelect){//单选
					_this.qcNode=null;
				}else{//多选移除
					var _index=-1;
					for(var i=0;i<_this.qcNode.length;i++){
						if(_this.qcNode[i][_this.valField]==this.id.replace('qli_','')){
							_index=i;
							break;
						}
					}
					if(_index!=-1){
						_this.qcNode.splice(_index,1);
					}
				}								
			}
			$(this).addClass(_this.hoverCls);
			
			
			if(_this.onSelected){
				_this.onSelected.call(_this,_this.findQNode(this.id),this);
			}
			
		});
		
		
		$('#sp_'+this.renderTo+' input[name="status"]').live('click',function(){
			_this.loadUser(_this.fatherid);
		});
		
		Chenxin.UI.RichModelTreeCombo.superclass.initEvent.call(this);
	},
	initComponent:function(){
		this.qStore=[];
		Chenxin.UI.RichModelTreeCombo.superclass.initComponent.call(this);		
		this.createModel();
		this.createQuickDiv();
		if(!this.singleSelect){
			this.qcNode=[];
		}
	}
});

Chenxin.UI.Menu=Chenxin.extend(null,{
	cls:'x-menu',						//样式
	id:'',						//按钮ID
	domCls:'x-menu-dom',					//选项容器样式
	hoverCls:'x-menu-items-hover',				//选项鼠标滑过样式
	itemsCls:'x-menu-items',				//选项样式
	hideAfterClick:true,
	createItems:function(){
		
		for(var i=0;i<this.items.length;i++){
			var item=this.items[i];	
			var _this=this;
			if(item=='-'||item=='|'){
				this.dom.append('<hr/>');
			}else{				
				var _li=document.createElement('li');			
				_li.innerHTML=(item.icon||'')+'<span>'+item.text+'</span>';
				_li.title=item.title||item.text;
				_li.className=this.itemsCls+(item.cls?(' '+item.cls):'');
				if(item.handler){
					$(_li).bind('click',{scope:item.scope||this.scope,fn:item.handler},function(e){
						e.data.fn.call(e.data.scope,this,e);
						if(_this.hideAfterClick){
							_this.hideMenu();
						}
					});
					$(_li).bind('mouseover',{scope:this},function(e){
						$(this).addClass(e.data.scope.hoverCls);
					});
					$(_li).bind('mouseleave',{scope:this},function(e){
						$(this).removeClass(e.data.scope.hoverCls);
					});
				}
			}
			this.dom.append(_li);
		}
	},
	createDom:function(){
		this.dom=$(document.createElement('ul'));
		this.dom.addClass(this.domCls);
		this.dom.hide();
		this.dom.appendTo(document.body);
		
		var intervalHide=null;
		var _this=this;	
		
		$(this.dom).bind('mouseleave',{scope:this},function(e){	
			intervalHide=setTimeout(function(){
				e.data.scope.hideMenu();
			},1000)
		});
		
		$(this.dom).bind('mouseenter',function(){	
			if(intervalHide!=null){
				clearTimeout(intervalHide);
			}
		});
		
	},
	hideMenu:function(){
		this.dom.hide();	
	},
	showMenu:function(){
		var offset=this.el.offset();
		this.dom.css('left',offset.left+'px');
		
		if(this.dom.height()+offset.top+this.el.innerHeight()>document.body.clientHeight){
			this.dom.css('top',offset.top-this.dom.height());
		}else{
			this.dom.css('top',offset.top+this.el.innerHeight()+'px');
		}
		this.dom.show();

		
	},
	initEvent:function(){
		this.el.bind('click',{scope:this},function(e){
			e.data.scope.showMenu.call(e.data.scope);
		});
	},
	
	initComponent:function(){
		if(!this.id){
			throw new Error('Id is need!');
		}
		this.scope=this.scope||this;
		this.el=$('#'+this.id);
		this.el.addClass(this.cls);
		this.createDom();
		this.createItems();
		this.initEvent();
	}
});

Chenxin.UI.Tab=Chenxin.extend(null,{
	id:'',
	mainCls:'x-tab-main',
	tabCls:'x-tab-title',
	headCls:'x-tab-head',
	bodyCls:'x-tab-body',
	activeCls:'x-tab-active',
	numalCls:'x-tab-numal',
	activeIndex:0,
	tabWidth:100,
	height:400,
	afterActive:Chenxin.emptyFn,
	activeTab:function(index){		
		this.tabTList.eq(this.activeIndex).removeClass(this.activeCls);
		this.tabTList.eq(this.activeIndex).addClass(this.numalCls);
		this.tabCList.eq(this.activeIndex).hide();
		this.activeIndex=index;
		this.tabTList.eq(this.activeIndex).removeClass(this.numalCls);
		this.tabTList.eq(this.activeIndex).addClass(this.activeCls);
		this.tabCList.eq(this.activeIndex).show();
		
		if(this.afterActive){
			this.afterActive.call(index);
		}
	},
	init:function(){
		var _this=this;
		this.el.addClass(this.mainCls);
		this.headDom.addClass(this.headCls);
		this.bodyDom.addClass(this.bodyCls);
		
		this.tabCList.hide();
		this.tabTList.each(function(i){
			this.index=i;
			$(this).width(_this.tabWidth);
			$(this).append('<span></span>');
			$(this).addClass(_this.tabCls);
			$(this).addClass(_this.numalCls);
			
			
			$(this).bind('click',function(){
				if(this.index==_this.activeIndex){
					return;
				}
				_this.activeTab(this.index);
			});
			
		});
		this.activeTab(this.activeIndex);
	},
	initComponent:function(){
		this.el=$('#'+this.id);
		this.headDom=$('#'+this.id+'>ul');
		this.bodyDom=$('#'+this.id+'>div');		
		this.tabTList=$('#'+this.id+'>ul>li');
		this.tabCList=$('#'+this.id+'>div>div');
		
		this.init();
	}
});

$(document).ready(function(){
	Chenxin.Fn.RegistDatePicker();
});
if (jQuery) (
	function(jQuery) {
	    jQuery.extend(jQuery.fn, {
	        defText: function(options) {
	            jQuery(this).each(function() {
	                var settings = jQuery.extend({
	                    deftxt: '请输入...'
	                }, options);
	                this.value = settings.deftxt;


	                this.defVal = settings.deftxt;
	                $(this).bind('click', function() {
	                    if (this.value == this.defVal) {
	                        this.value = '';
	                    }
	                });
	                $(this).bind('blur', function() {
	                    if (this.value == '') {
	                        this.value = this.defVal;
	                    }
	                });

	            });
	        },
	        numberText: function(options) {

	            jQuery(this).each(function() {

	                var settings = jQuery.extend({
	                    acceptEnter: true,
	                    minValue: undefined,
	                    maxValue: undefined,
	                    acceptDecimal: true//接受小数点
	                }, options);

	                //var _oldValue=0;

	                $(this).bind('keydown', function(e) {
	                    //_oldValue=parseFloat(this.value);
	                    if (settings.acceptEnter && e.keyCode == 13) {//Enter
	                        return true;
	                    }
	                    if (e.keyCode == 8) {//BackSpace BackSpace 
	                        return true;
	                    }
	                    if (e.keyCode == 9) {//Tab 
	                        return true;
	                    }
	                    if (e.keyCode == 46) {//Delete
	                        return true;
	                    }
	                    if ((e.keyCode > 46 && e.keyCode < 58) || (e.keyCode > 95 && e.keyCode < 106)) {//number
	                        return true;
	                    }
	                    if (settings.acceptDecimal && (e.keyCode == 190 || e.keyCode == 110)) {//Decimal
	                        return true;
	                    }
	                    return false;
	                });
	                $(this).bind('change', function(e) {
	                    var _newValue = parseFloat(this.value);
	                    if (settings.minValue != undefined && _newValue < settings.minValue) {
	                        if (this.defVal) {
	                            this.value = this.defVal;
	                        } else {
	                            this.value = '';
	                        }
	                    }
	                    if (settings.maxValue != undefined && _newValue > settings.maxValue) {
	                        if (this.defVal) {
	                            this.value = this.defVal;
	                        } else {
	                            this.value = '';
	                        }
	                    }
	                });
	            });
	        }
	    })
	})(jQuery);